为全局使用配置 AutoMapper 的正确方法是什么。
我想设置一次,然后在整个应用程序中使用。
我有一种强烈的感觉,这是错误的。 事实上,我知道这是错误的,因为这会调用一个新实例。 我想要一个全局配置,然后你怎么调用它。 找不到好的例子!
这就是我得到的:但这不是我想要的
public static class AutoMapperConfig
{
public static IMapper GetMapper()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<R_Logo, LogoDto>();
//lots more maps...?
});
IMapper mapper = config.CreateMapper();
return mapper;
}
}
然后是用法:
var imapper = AutoMapperConfig.GetMapper();
var dest = imapper.Map<R_Logo, LogoDto>(logo);
更新基于:pinkfloydx33
调用一次,然后配置完成。
public static class AutoMapperConfig
{
public static void RegisterMappings()
{
AutoMapper.Mapper.Initialize(cfg => {
cfg.CreateMap<R_Logo, LogoDto>();
/* etc */
});
}
}
最佳答案
这是在 asp.net core mvc 中配置自动映射器的步骤。
1. 创建从 Profile
public class ClientMappingProfile : Profile
{
public ClientMappingProfile ()
{
CreateMap<R_Logo, LogoDto>().ReverseMap();
}
}
2.创建 AutoMapper 配置类并在此处添加您的映射配置文件类。
public class AutoMapperConfiguration
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ClientMappingProfile>();
});
return config;
}
}
3.我们如何使用它。
var config = new AutoMapperConfiguration().Configure();
var iMapper = config.CreateMapper();
var dest = iMapper.Map<R_Logo, LogoDto>(logo);
关于c# - AutoMapper 5.2如何配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508231/