.net6.0 webapi demo

Services.cs 3.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using AutoMapper;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using System.Reflection;
  4. namespace Net6Demo_Api.Util
  5. {
  6. public static partial class Extention
  7. {
  8. /// <summary>
  9. /// 使用AutoMapper自动映射拥有MapAttribute的类
  10. /// </summary>
  11. /// <param name="services">服务集合</param>
  12. /// <param name="configure">自定义配置</param>
  13. public static IServiceCollection AddAutoMapper(this IServiceCollection services)
  14. {
  15. List<(Type from, Type[] targets)> maps = new List<(Type from, Type[] targets)>();
  16. maps= GlobalData.AllFxTypes.Where(x => x.GetCustomAttribute<MapAttribute>() != null)
  17. .Select(x => (x, x.GetCustomAttribute<MapAttribute>().TargetTypes)).ToList();
  18. var configuration = new MapperConfiguration(cfg =>
  19. {
  20. cfg.ClearPrefixes();
  21. cfg.RecognizePrefixes("F_");
  22. cfg.RecognizeDestinationPrefixes("F_");
  23. maps.ForEach(aMap =>
  24. {
  25. aMap.targets.ToList().ForEach(aTarget =>
  26. {
  27. cfg.CreateMap(aMap.from, aTarget).ReverseMap();
  28. });
  29. });
  30. cfg.AddMaps(GlobalData.AllFxAssemblies);
  31. });
  32. services.AddSingleton(configuration.CreateMapper());
  33. return services;
  34. }
  35. /// <summary>
  36. /// 自动注入拥有ITransientDependency,IScopeDependency或ISingletonDependency的类
  37. /// </summary>
  38. /// <param name="services"></param>
  39. public static void AddFxServices(this IServiceCollection services)
  40. {
  41. Dictionary<Type, ServiceLifetime> lifeTimeMap = new Dictionary<Type, ServiceLifetime>
  42. {
  43. { typeof(ITransientDependency), ServiceLifetime.Transient},
  44. { typeof(IScopedDependency),ServiceLifetime.Scoped},
  45. { typeof(ISingletonDependency),ServiceLifetime.Singleton}
  46. };
  47. GlobalData.AllFxTypes.ForEach(aType =>
  48. {
  49. lifeTimeMap.ToList().ForEach(aMap =>
  50. {
  51. var theDependency = aMap.Key;
  52. if (theDependency.IsAssignableFrom(aType) && theDependency != aType)
  53. {
  54. Type[] interfaces = aType.GetInterfaces();
  55. interfaces.ToList().ForEach(i =>
  56. {
  57. services.Add(new ServiceDescriptor(i, aType, aMap.Value));
  58. });
  59. services.Add(new ServiceDescriptor(aType, aType, aMap.Value));
  60. }
  61. });
  62. });
  63. }
  64. }
  65. /// <summary>
  66. /// 注入标记,生命周期为Transient
  67. /// </summary>
  68. public interface ITransientDependency
  69. {
  70. }
  71. /// <summary>
  72. /// 注入标记,生命周期为Singleton
  73. /// </summary>
  74. public interface ISingletonDependency
  75. {
  76. }
  77. /// <summary>
  78. /// 注入标记,生命周期为Scope
  79. /// </summary>
  80. public interface IScopedDependency
  81. {
  82. }
  83. }