AppServiceExtensions.cs 3.0 KB

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