AppServiceExtensions.cs 2.6 KB

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