-
Notifications
You must be signed in to change notification settings - Fork 11
Qf.Core.AutoMapper的用法
非空 edited this page Feb 19, 2020
·
4 revisions
引用 Qf.Core.AutoMapper
NuGet包
添加Profile
映射配置文件
public class ApplicationAutoMapperProfile : Profile
{
public ApplicationAutoMapperProfile()
{
//在这里添加要映射的对象及其相关配置
CreateMap<CreateTodoTaskInput, TodoTask>();
}
}
在静态类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
对象,调用 IObjectMapper
的 Map<,>()
方法获取映射对象
具体用法请参考示例项目 Qf.SysTodoList