AppServiceExtensions.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Attribute;
  2. using Base;
  3. using Services;
  4. using System.Reflection;
  5. namespace Infrastructure
  6. {
  7. /// <summary>
  8. /// App服务注册
  9. /// </summary>
  10. public static class AppServiceExtensions
  11. {
  12. /// <summary>
  13. /// 注册引用程序域中所有有AppService标记的类的服务
  14. /// </summary>
  15. /// <param name="services"></param>
  16. public static void AddAppService(this IServiceCollection services)
  17. {
  18. // var cls = AppSettings.Get<string[]>("InjectClass");
  19. // if (cls == null || cls.Length <= 0)
  20. // {
  21. // throw new Exception("请更新appsettings类");
  22. // }
  23. // foreach (var item in cls)
  24. // {
  25. // Register(services, item);
  26. // }
  27. // services.AddTransient<ISysOperLogService, SysOperLogService>();
  28. }
  29. private static void Register(IServiceCollection services, string item)
  30. {
  31. Assembly assembly = Assembly.Load(item);
  32. foreach (var type in assembly.GetTypes())
  33. {
  34. var serviceAttribute = type.GetCustomAttribute<AppServiceAttribute>();
  35. if (serviceAttribute != null)
  36. {
  37. var serviceType = serviceAttribute.ServiceType;
  38. //情况1 适用于依赖抽象编程,注意这里只获取第一个
  39. if (serviceType == null && serviceAttribute.InterfaceServiceType)
  40. {
  41. serviceType = type.GetInterfaces().FirstOrDefault();
  42. }
  43. //情况2 不常见特殊情况下才会指定ServiceType,写起来麻烦
  44. if (serviceType == null)
  45. {
  46. serviceType = type;
  47. }
  48. switch (serviceAttribute.ServiceLifetime)
  49. {
  50. case LifeTime.Singleton:
  51. services.AddSingleton(serviceType, type);
  52. break;
  53. case LifeTime.Scoped:
  54. services.AddScoped(serviceType, type);
  55. break;
  56. case LifeTime.Transient:
  57. services.AddTransient(serviceType, type);
  58. break;
  59. default:
  60. services.AddTransient(serviceType, type);
  61. break;
  62. }
  63. //System.Console.WriteLine($"注册:{serviceType}");
  64. }
  65. }
  66. }
  67. }
  68. }