AppServiceExtensions.cs 2.7 KB

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