AppServiceExtensions.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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<IMakeTemplateGategoryService, MakeTemplateGategoryService>();
  31. services.AddTransient<IMakeTemplateService, MakeTemplateService>();
  32. services.AddTransient<IMakeDataService, MakeDataService>();
  33. services.AddTransient<IMakeFilesService, MakeFilesService>();
  34. services.AddTransient<IFilesForAllService, FilesForAllService>();
  35. services.AddTransient<IVersionsService, VersionsService>();
  36. services.AddTransient<IVersionForProjectService, VersionForProjectService>();
  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. }