C#使用AutoMapper實現類映射詳解
寫在前面
AutoMapper是一個用于.NET中簡化類之間的映射的擴展庫;可以在執(zhí)行對象映射的過程,省去的繁瑣轉換代碼,實現了對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類映射內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#通過Python.NET調用Python?pyd擴展模塊的實踐指南
在工業(yè)軟件與算法融合的場景中,經常需要將 Python 生態(tài)的高性能算法庫集成到 C# 桌面或后端應用中,下面我們就來看看在C#應用中調用Python編譯模塊(pyd)有哪些技術方案吧2026-05-05
c#用Treeview實現FolderBrowerDialog 和動態(tài)獲取系統圖標(運用了Win32 
其實,FolderBrowerDialog 很好用呢,有木有啊親,反正我特別的喜歡,微軟大哥把這個瀏覽文件夾的東東封裝的多好呀2013-03-03
DevExpress實現禁用TreeListNode CheckBox的方法
這篇文章主要介紹了DevExpress實現禁用TreeListNode CheckBox的方法,在項目開發(fā)中有應用價值,需要的朋友可以參考下2014-08-08

