C#使用AutoMapper实现类映射详解
作者:rjcql
AutoMapper是一个用于.NET中简化类之间的映射的扩展库,这篇文章主要介绍了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类映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!