C#使用AutoMapper实现类映射详解
写在前面
AutoMapper是一个用于.NET中简化类之间的映射的扩展库;可以在执行对象映射的过程,省去的繁琐转换代码,实现了对DTO的快速装配,有效的减少了代码量。
通过NuGet安装,AutoMapper, 由于本例用到了DI,所以需要顺便安装一下 AutoMapper.Extensions.Microsoft.DependencyInjection

代码实现
using AutoMapper;
using AutoMapper.Internal;
using Microsoft.Extensions.DependencyInjection;
IServiceCollection services = new ServiceCollection();
services.AddTransient<ISomeService>(sp => new FooService(5));
services.AddAutoMapper(typeof(Source));
var provider = services.BuildServiceProvider();
using (var scope = provider.CreateScope())
{
var mapper = scope.ServiceProvider.GetRequiredService<IMapper>();
foreach (var typeMap in mapper.ConfigurationProvider.Internal().GetAllTypeMaps())
{
Console.WriteLine($"{typeMap.SourceType.Name} -> {typeMap.DestinationType.Name}");
}
foreach (var service in services)
{
Console.WriteLine(service.ServiceType + " - " + service.ImplementationType);
}
var dest = mapper.Map<Dest2>(new Source2());
Console.WriteLine(dest!.ResolvedValue);
}
Console.ReadKey();
public class Source
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Dest
{
public int ResolvedValue { get; set; }
}
public class Source2
{
public string Name { get; set; }
public int ResolvedValue { get; set; }
}
public class Dest2
{
public int ResolvedValue { get; set; }
}
/// <summary>
/// 映射表1
/// </summary>
public class Profile1 : Profile
{
public Profile1()
{
CreateMap<Source, Dest>();
}
}
/// <summary>
/// 映射表1
/// </summary>
public class Profile2 : Profile
{
public Profile2()
{
CreateMap<Source2, Dest2>()
.ForMember(d => d.ResolvedValue, opt => opt.MapFrom<DependencyResolver>());
}
}
public class DependencyResolver : IValueResolver<object, object, int>
{
private readonly ISomeService _service;
public DependencyResolver(ISomeService service)
{
_service = service;
}
public int Resolve(object source, object destination, int destMember, ResolutionContext context)
{
return _service.Modify(destMember);
}
}
public interface ISomeService
{
int Modify(int value);
}
public class FooService : ISomeService
{
private readonly int _value;
public FooService(int value)
{
_value = value;
}
public int Modify(int value) => value + _value;
}调用示例

到此这篇关于C#使用AutoMapper实现类映射详解的文章就介绍到这了,更多相关C# AutoMapper类映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
C#通过Python.NET调用Python pyd扩展模块的实践指南
在工业软件与算法融合的场景中,经常需要将 Python 生态的高性能算法库集成到 C# 桌面或后端应用中,下面我们就来看看在C#应用中调用Python编译模块(pyd)有哪些技术方案吧2026-05-05
c#用Treeview实现FolderBrowerDialog 和动态获取系统图标(运用了Win32 
其实,FolderBrowerDialog 很好用呢,有木有啊亲,反正我特别的喜欢,微软大哥把这个浏览文件夹的东东封装的多好呀2013-03-03
DevExpress实现禁用TreeListNode CheckBox的方法
这篇文章主要介绍了DevExpress实现禁用TreeListNode CheckBox的方法,在项目开发中有应用价值,需要的朋友可以参考下2014-08-08


最新评论