AutoMapper 9.0的改造(续)
发布日期:2021-08-13 07:45:05 浏览次数:3 分类:技术文章

本文共 2847 字,大约阅读时间需要 9 分钟。

上一篇有一个读者,有疑问,如何自动化注册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
() != null) .Select(_type => _type.GetCustomAttribute
()); 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
(); 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
(); var factory = serviceProvider.GetRequiredService
(); 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
(); factory.AddAssemblys(assemblys); } }

在Startup.Configure方法内调用一下

 

看看测试

 

增加一个测试控制器

执行结果

 

 

转载于:https://www.cnblogs.com/NCoreCoder/p/11453443.html

转载地址:https://blog.csdn.net/weixin_30679823/article/details/101501508 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:.Net Core 3.0下AOP试水~~
下一篇:.Net Core 3.0依赖注入替换 Autofac

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月23日 19时47分05秒