AppServiceExtensions.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. //必须注册的service
  28. services.AddTransient<IHdBindRecordService, HdBindRecordService>();
  29. services.AddTransient<IHdTradeRecordService, HdTradeRecordService>();
  30. services.AddTransient<IHdUnBindRecordService, HdUnBindRecordService>();
  31. services.AddTransient<IHdChangeRecordService, HdChangeRecordService>();
  32. }
  33. private static void Register(IServiceCollection services, string item)
  34. {
  35. Assembly assembly = Assembly.Load(item);
  36. foreach (var type in assembly.GetTypes())
  37. {
  38. var serviceAttribute = type.GetCustomAttribute<AppServiceAttribute>();
  39. if (serviceAttribute != null)
  40. {
  41. var serviceType = serviceAttribute.ServiceType;
  42. //情况1 适用于依赖抽象编程,注意这里只获取第一个
  43. if (serviceType == null && serviceAttribute.InterfaceServiceType)
  44. {
  45. serviceType = type.GetInterfaces().FirstOrDefault();
  46. }
  47. //情况2 不常见特殊情况下才会指定ServiceType,写起来麻烦
  48. if (serviceType == null)
  49. {
  50. serviceType = type;
  51. }
  52. switch (serviceAttribute.ServiceLifetime)
  53. {
  54. case LifeTime.Singleton:
  55. services.AddSingleton(serviceType, type);
  56. break;
  57. case LifeTime.Scoped:
  58. services.AddScoped(serviceType, type);
  59. break;
  60. case LifeTime.Transient:
  61. services.AddTransient(serviceType, type);
  62. break;
  63. default:
  64. services.AddTransient(serviceType, type);
  65. break;
  66. }
  67. //System.Console.WriteLine($"注册:{serviceType}");
  68. }
  69. }
  70. }
  71. }
  72. }