| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using AutoMapper;
- using Microsoft.Extensions.DependencyInjection;
- using System.Reflection;
- namespace Net6Demo_Api.Util
- {
- public static partial class Extention
- {
- /// <summary>
- /// 使用AutoMapper自动映射拥有MapAttribute的类
- /// </summary>
- /// <param name="services">服务集合</param>
- /// <param name="configure">自定义配置</param>
- public static IServiceCollection AddAutoMapper(this IServiceCollection services)
- {
- List<(Type from, Type[] targets)> maps = new List<(Type from, Type[] targets)>();
- maps= GlobalData.AllFxTypes.Where(x => x.GetCustomAttribute<MapAttribute>() != null)
- .Select(x => (x, x.GetCustomAttribute<MapAttribute>().TargetTypes)).ToList();
- var configuration = new MapperConfiguration(cfg =>
- {
- cfg.ClearPrefixes();
- cfg.RecognizePrefixes("F_");
- cfg.RecognizeDestinationPrefixes("F_");
- maps.ForEach(aMap =>
- {
- aMap.targets.ToList().ForEach(aTarget =>
- {
- cfg.CreateMap(aMap.from, aTarget).ReverseMap();
- });
- });
- cfg.AddMaps(GlobalData.AllFxAssemblies);
- });
- services.AddSingleton(configuration.CreateMapper());
- return services;
- }
- /// <summary>
- /// 自动注入拥有ITransientDependency,IScopeDependency或ISingletonDependency的类
- /// </summary>
- /// <param name="services"></param>
- public static void AddFxServices(this IServiceCollection services)
- {
- Dictionary<Type, ServiceLifetime> lifeTimeMap = new Dictionary<Type, ServiceLifetime>
- {
- { typeof(ITransientDependency), ServiceLifetime.Transient},
- { typeof(IScopedDependency),ServiceLifetime.Scoped},
- { typeof(ISingletonDependency),ServiceLifetime.Singleton}
- };
- GlobalData.AllFxTypes.ForEach(aType =>
- {
- lifeTimeMap.ToList().ForEach(aMap =>
- {
- var theDependency = aMap.Key;
- if (theDependency.IsAssignableFrom(aType) && theDependency != aType)
- {
- Type[] interfaces = aType.GetInterfaces();
- interfaces.ToList().ForEach(i =>
- {
- services.Add(new ServiceDescriptor(i, aType, aMap.Value));
- });
- services.Add(new ServiceDescriptor(aType, aType, aMap.Value));
- }
- });
- });
- }
- }
- /// <summary>
- /// 注入标记,生命周期为Transient
- /// </summary>
- public interface ITransientDependency
- {
- }
- /// <summary>
- /// 注入标记,生命周期为Singleton
- /// </summary>
- public interface ISingletonDependency
- {
- }
- /// <summary>
- /// 注入标记,生命周期为Scope
- /// </summary>
- public interface IScopedDependency
- {
- }
- }
|