AppServiceExtensions.cs 2.6 KB

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