我试图弄清楚如何在Global.asax级别上配置新的AutoMapper。
我以前对旧的AutoMapper执行以下操作:
在App_Start文件夹中创建一个名为MappingProfile.cs的类,并在构造函数中添加如下所示的映射:
public MappingProfile()
{
Mapper.CreateMap<Product, ProductDto>();
Mapper.CreateMap<ApplicationUser, UserDto>();
}
然后在Global.asax中调用:
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
有人可以告诉我如何使用新版本的AutoMapper实现上述目标吗?我一直在阅读文档,但似乎无法理解。
我相信我在MappingProfile.cs文件中做了这样的事情:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductDto>();
cfg.CreateMap<ApplicationUser, UserDto>();
});
但是我该如何使用config变量?
这就是我的方法。
public abstract class AutoMapperBase
{
protected readonly IMapper _mapper;
protected AutoMapperBase()
{
var config = new MapperConfiguration(x =>
{
x.CreateMap<Product, ProductDto>();
x.CreateMap<ApplicationUser, UserDto>();
});
_mapper = config.CreateMapper();
}
}
然后从需要使用它的任何类继承AutoMapperBase,并这样调用它:
var foo = _mapper.Map<ProductDto>(someProduct);
您不再需要在Global.asax中声明或配置它
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句