AppServiceExtensions.cs 3.4 KB

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