Skip to content

Qf.Core.AutoMapper的用法

非空 edited this page Feb 19, 2020 · 4 revisions

如何使用 Qf.Core.AutoMapper 来完成对象映射

Application项目

引用 Qf.Core.AutoMapper NuGet包

添加Profile映射配置文件

public class ApplicationAutoMapperProfile : Profile
{
    public ApplicationAutoMapperProfile()
    {
        //在这里添加要映射的对象及其相关配置
        CreateMap<CreateTodoTaskInput, TodoTask>();
    }
}

WebApi项目

在静态类CustomExtensionsMethods添加以下扩展方法:

public static IServiceCollection AddAutoMapper(this IServiceCollection services, IConfiguration configuration)
{
    services.AddAutoMapperObjectMapper();
    services.Configure<AutoMapperOptions>(options =>
    {
        options.AddProfile<ApplicationAutoMapperProfile>();
    });
    return services;
}

Startup类的ConfigureServices方法中引用该扩展方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(Configuration);
    ...
}

修改AddCustomDbContext方法,添加对IObjectMapper的注入代码

services.AddAssembly(typeof(IObjectMapper).Assembly);

同时在Configure方法中使用AutoMapper的扩展方法UseQfAutoMapper:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseHttpsRedirection();

    app.UseQfAutoMapper();

    app.UseRouting();
    ...
}

用法

public class CreateTodoTaskCommandHandler : IRequestHandler<CreateTodoTaskCommand, bool>
{
    private readonly IObjectMapper _objectMapper;
    private readonly IRepository<TodoTask, Guid> _repository;

    public CreateTodoTaskCommandHandler(IObjectMapper objectMapper,
        IRepository<TodoTask, Guid> repository)
    {
        _objectMapper = objectMapper ?? throw new ArgumentNullException(nameof(objectMapper));
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
    }
    public async Task<bool> Handle(CreateTodoTaskCommand message, CancellationToken cancellationToken)
    {
        var model = _objectMapper.Map<CreateTodoTaskInput, TodoTask>(message.Data);
        model.CreationTime = DateTime.Now;
        await _repository.AddAsync(model, autoSave: true, cancellationToken);
        return true;
    }
}

注入IObjectMapper对象,调用 IObjectMapperMap<,>()方法获取映射对象

具体用法请参考示例项目 Qf.SysTodoList