欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用AutoMapper實(shí)現(xiàn)類映射詳解

 更新時(shí)間:2024年01月26日 08:33:34   作者:rjcql  
AutoMapper是一個(gè)用于.NET中簡(jiǎn)化類之間的映射的擴(kuò)展庫(kù),這篇文章主要介紹了C#如何使用AutoMapper實(shí)現(xiàn)類映射,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

寫(xiě)在前面

AutoMapper是一個(gè)用于.NET中簡(jiǎn)化類之間的映射的擴(kuò)展庫(kù);可以在執(zhí)行對(duì)象映射的過(guò)程,省去的繁瑣轉(zhuǎn)換代碼,實(shí)現(xiàn)了對(duì)DTO的快速裝配,有效的減少了代碼量。

通過(guò)NuGet安裝,AutoMapper, 由于本例用到了DI,所以需要順便安裝一下 AutoMapper.Extensions.Microsoft.DependencyInjection

代碼實(shí)現(xiàn)

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;
}

調(diào)用示例

到此這篇關(guān)于C#使用AutoMapper實(shí)現(xiàn)類映射詳解的文章就介紹到這了,更多相關(guān)C# AutoMapper類映射內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論