我正在使用现有的解决方案.该解决方案使用Windsor IoC.我有一个AutomapperMappings.cs看起来像这样的课程:
public class AutoMapperMappings
{
public static void Configure()
{
AutoMapper.Mapper.Configuration
.CreateMap<LatestUpdateModel, LatestUpdate>();
AutoMapper.Mapper.Configuration
.CreateMap<LatestUpdate, LatestUpdateModel>();
AutoMapper.Mapper.Configuration
.CreateMap<DownloadLinkModel, DownloadLink>();
AutoMapper.Mapper.Configuration
.CreateMap<DownloadLink, DownloadLinkModel>();
AutoMapper.Mapper.Configuration
.CreateMap<NavigationElementModel, NavigationElement>();
AutoMapper.Mapper.Configuration
.CreateMap<NavigationElement, NavigationElementModel>();
AutoMapper.Mapper.Configuration
.CreateMap<Promobox, PromoboxModel>();
AutoMapper.Mapper.Configuration
.CreateMap<PromoboxModel, Promobox>();
}
}
Run Code Online (Sandbox Code Playgroud)
在我Global.asax,我有以下内容:
protected void Application_Start(object sender, EventArgs e)
{
IoCContainer();
ConfigureAutoMapperMappings();
}
protected virtual void ConfigureAutoMapperMappings()
{
AutoMapperMappings.Configure();
}
Run Code Online (Sandbox Code Playgroud)
以上是给我一个警告说我应该放弃静态API.所以我用Google搜索并做了一些阅读,建议我改变我的意思AutomapperMappings.cs:
public class AutoMapperMappings
{
public static void Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<LatestUpdateModel, LatestUpdate>();
cfg.CreateMap<LatestUpdate, LatestUpdateModel>();
cfg.CreateMap<DownloadLinkModel, DownloadLink>();
cfg.CreateMap<DownloadLink, DownloadLinkModel>();
cfg.CreateMap<NavigationElementModel, NavigationElement>();
cfg.CreateMap<NavigationElement, NavigationElementModel>();
cfg.CreateMap<Promobox, PromoboxModel>();
cfg.CreateMap<PromoboxModel, Promobox>();
});
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但变量var config实际上并没有在任何地方使用,所以我确定我需要做更多的东西,但我不知道我需要改变什么和在哪里.
有一个教程"从静态API迁移".
您需要创建mapper对象并将其注册到IoC容器:
public class AutoMapperMappings
{
public static void Configure(IWindsorContainer container)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<LatestUpdateModel, LatestUpdate>();
...
});
var mapper = config.CreateMapper();
// register your mapper here.
container.Register(Component.For<IMapper>().Instance(mapper));
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以将映射器注入需要映射实体的类:
public class ExampleClass
{
private readonly IMapper _mapper;
public ExampleClass(IMapper mapper)
{
_mapper = mapper;
}
public void DoWork()
{
var model = new LatestUpdateModel();
...
var update = mapper.Map<LatestUpdateModel, LatestUpdate>(model);
}
}
Run Code Online (Sandbox Code Playgroud)
此迁移将通过创建模拟对象到IMapper接口来帮助您使代码更易于测试.
| 归档时间: |
|
| 查看次数: |
4915 次 |
| 最近记录: |