AutoMapper 9.0的改造(续)
生活随笔
收集整理的這篇文章主要介紹了
AutoMapper 9.0的改造(续)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上一篇有一個讀者,有疑問,如何自動化注冊Dto
我開篇,做了一個自動化注冊的
public sealed class AutoInjectAttribute : Attribute{public Type SourceType { get; }public Type TargetType { get; }public AutoInjectAttribute(Type sourceType, Type targetType){SourceType = sourceType;TargetType = targetType;}}增加了一個特性,在Dto上面打上,參數1是源類型,參數2是Dto類型
增加一個工廠類保存自動轉換的類型
public class AutoInjectFactory{public List<(Type,Type)> ConvertList { get; } = new List<(Type, Type)>();public void AddAssemblys(params Assembly[] assemblys){foreach (var assembly in assemblys){var atributes = assembly.GetTypes().Where(_type => _type.GetCustomAttribute<AutoInjectAttribute>() != null).Select(_type => _type.GetCustomAttribute<AutoInjectAttribute>());foreach (var atribute in atributes){ConvertList.Add((atribute.SourceType, atribute.TargetType));}}}}在原來的AddAutoMapper上找到修改的代碼段
public static IServiceCollection AddAutoMapper(this IServiceCollection service){...略service.TryAddSingleton(serviceProvider =>{var mapperConfigurationExpression = serviceProvider.GetRequiredService<MapperConfigurationExpression>();var instance = new MapperConfiguration(mapperConfigurationExpression);instance.AssertConfigurationIsValid();return instance;});...略return service;}改為
public static IServiceCollection AddAutoMapper(this IServiceCollection service){...略service.TryAddSingleton(serviceProvider =>{var mapperConfigurationExpression = serviceProvider.GetRequiredService<MapperConfigurationExpression>();var factory = serviceProvider.GetRequiredService<AutoInjectFactory>();foreach (var (sourceType,targetType) in factory.ConvertList){mapperConfigurationExpression.CreateMap(sourceType, targetType);}var instance = new MapperConfiguration(mapperConfigurationExpression);instance.AssertConfigurationIsValid();return instance;});...略return service;}增加一組擴展方法
public static class AutoMapperExtension{...略public static void UseAutoInject(this IApplicationBuilder applicationBuilder, params Assembly[] assemblys){var factory = applicationBuilder.ApplicationServices.GetRequiredService<AutoInjectFactory>();factory.AddAssemblys(assemblys);}}在Startup.Configure方法內調用一下
?
看看測試
?
增加一個測試控制器
執行結果
?
?
轉載于:https://www.cnblogs.com/NCoreCoder/p/11453443.html
總結
以上是生活随笔為你收集整理的AutoMapper 9.0的改造(续)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬取百度迁徙_Python爬
- 下一篇: WinRAR注册+去广告教程