我有一个非常简单的问题...是否可以像这样设置自动映射器:
public IMapper Init()
{
var config = new MapperConfiguration(cfg =>
{
cfg = MappingModelsToViewModels(cfg);
});
return config.CreateMapper();
}
我将每个映射拆分为这样的方法:
public IMapperConfigurationExpression MappingModelsToViewModels(IMapperConfigurationExpression cfg)
{
cfg = SKU(cfg);
cfg = Lot(cfg);
cfg = SalesRate(cfg);
cfg = SpecialSalesRate(cfg);
cfg = Order(cfg);
//...
return cfg;
}
public IMapperConfigurationExpression SKU(IMapperConfigurationExpression cfg)
{
// HTTPGET
cfg.CreateMap<SKU, SKUViewModel>() //...
return cfg;
}
我问是因为我收到此错误:
映射器未初始化。调用 使用适当的初始化 配置。如果您尝试通过 容器或其他方式,请确保没有任何调用 静态 Mapper.Map 方法,如果您使用的是 ProjectTo 或 使用作为数据源扩展方法,请确保传入 适当的 IConfigurationProvider 实例。
我通过将部分映射代码移动到新的 MapperConfiguration 中进行了测试,它正在工作。
谢谢
大卫
方法可以配置自动映射程序。我个人喜欢以下方法——
Global.ascx.cs
protected void Application_Start()
{
...
AutoMapperConfiguration.Initialize();
...
}
自动映射器配置.cs
public static class AutoMapperConfiguration
{
public static void Initialize()
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SKU, SKUViewModel>();
cfg.CreateMap<SKUViewModel, SKU>();
cfg.CreateMap<Lot, LotViewModel>();
cfg.CreateMap<LotViewModel, Lot>();
});
Mapper = MapperConfiguration.CreateMapper();
}
public static IMapper Mapper { get; private set; }
public static MapperConfiguration MapperConfiguration { get; private set; }
}
用法
用法会像——
SKUViewModel model = AutoMapperConfiguration.Mapper.Map<SKU, SKUViewModel>(sku);
单元测试
[Test]
public void AutoMapperConfigurationInitializeValid()
{
AutoMapperConfiguration.Initialize();
AutoMapperConfiguration.MapperConfiguration.AssertConfigurationIsValid();
}
我通常通过使用automapper
具有的profile
选项来完成此操作。如果既提供了灵活性,又减少了以后修改的地方-
配置文件定义,通过从类派生AutoMapper
Profile
完成-
public class Profile1 : Profile
{
public Profile1(){ //... for version < 5, use protected void Configure
CreateMap<SKU, SKUModel>()
//........
}
}
然后初始化自动映射器和加载配置文件 -
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile<Profile1>();
});
Mapper = MapperConfiguration.CreateMapper();
或者你可以让AutoMapper
自己检测配置文件 -
// Assembly objects
Mapper.Initialize(cfg => cfg.AddProfiles(/*.... supply the assembly here ...*/));
更多可以在这里找到 -
https://github.com/AutoMapper/AutoMapper/wiki/Configuration#profile-instances