AppServiceExtensions.cs 3.0 KB

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