我正在使用AutoMapper将我的模型转换为视图模型。我已经完成所有设置的配置,测试和工作。供参考,这是我的configure方法的外观:
public static MapperConfiguration Configure()
{
MapperConfiguration mapperConfiguration = new MapperConfiguration(cfg => {
cfg.CreateMap<Ebill, EbillHarvesterTaskVM>()
cfg.CreateMap<Note, NoteVM>();
cfg.CreateMap<LoginItem, LoginCredentialVM>()
cfg.CreateMap<Login, ProviderLoginVM>()
});
mapperConfiguration.CreateMapper();
return mapperConfiguration;
}
这是我的测试结果:
public void ValidConfigurationTest()
{
var config = AutoMapperConfig.Configure();
config.AssertConfigurationIsValid();
}
我不了解如何访问它,以将其从控制器中实际映射到另一个对象。我知道我的应用程序启动时可以调用此config方法,我有一个从global.asax调用的应用程序配置类,该类调用了我的automapper配置方法。我不确定如何从控制器内部访问所有这些。我已经读过一些有关依赖注入的内容,但是我对这意味着如何应用它还不够熟悉。
我过去使用过Automapper,但我想我实现了现在不可用的静态API。 config方法如下所示:
public static void RegisterMappings()
{
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<ManagementCompany, ManagementCompanyViewModel>();
cfg.CreateMap<ManagementCompanyViewModel, ManagementCompany>();
});
}
该配置在Global.asax中被调用
AutoMapperConfig.RegisterMappings();
以及您可以在控制器中调用此位置以利用映射的位置:
AutoMapper.Mapper.Map(managementCompany, managementCompanyVM);
这种方式不再起作用。当我键入AutoMapperMapper时,没有要调用的Map方法。我需要做些什么才能访问我的映射并使用它们?
public static MapperConfiguration Configure() {
MapperConfiguration mapperConfiguration = new MapperConfiguration(cfg => {
cfg.CreateMap<Ebill, EbillHarvesterTaskVM>()
cfg.CreateMap<Note, NoteVM>();
cfg.CreateMap<LoginItem, LoginCredentialVM>()
cfg.CreateMap<Login, ProviderLoginVM>()
});
return mapperConfiguration;
}
构建映射器,并将其注册到应用程序使用的依赖项容器。
global.asax
MapperConfiguration config = AutoMapperConfig.Configure();;
//build the mapper
IMapper mapper = config.CreateMapper();
//..register mapper with the dependency container used by your application.
myContainer.Register<IMapper>(mapper); //...this is just an oversimplified example
通过构造函数注入将控制器更新为显式依赖于映射器
private readonly IMapper mapper;
public MyController(IMapper mapper, ...) {
this.mapper = mapper;
//...
}
并根据需要在控制器操作中调用映射器。
//...
Note model = mapper.Map<Note>(noteVM);
//...