AppServiceExtensions.cs 3.1 KB

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