写在前面

AutoMapper是一个用于.NET中简化类之间的映射的扩展库;可以在执行对象映射的过程,省去的繁琐转换代码,实现了对DTO的快速装配,有效的减少了代码量。

通过NuGet安装,AutoMapper, 由于本例用到了DI,所以需要顺便安装一下 AutoMapper.Extensions.Microsoft.DependencyInjection

C# 使用AutoMapper实现类映射-LMLPHP

代码实现

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实现类映射-LMLPHP

01-26 11:53