我正在迁移到 newer configuration自动映射器。我在看 AutoMapper GitHub Wiki 上的例子并且对如何完成配置有点困惑。 Wiki 在一个地方说您可以将 MapperConfiguration 实例存储在您的 D.I 中。容器(或静态存储),但下一段说您可以静态存储 Mapper 实例。简而言之,我不确定我是否应该这样做
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo, Bar>().ReverseMap(); //creates a bi-directional mapping between Foo & Bar
cfg.AddProfile<FooProfile>(); //suppose FooProfile creates mappings...
});
然后使用 D.I. Unity 等容器来存储该实例......
container.RegisterInstance<MapperConfiguration>(config);
我以后可以在哪里使用这个实例来执行映射...
public void CreateMapping(MapperConfiguration config, Bar bar)
{
Foo foo = config.CreateMapper().Map(bar);
//do stuff with foo
}
或者,我应该存储 MapperConfiguration 生成的 IMapper 实例
container.RegisterInstance<IMapper>(config.CreateMapper());
用法如下
public void CreateMapping(IMapper mapper, Bar bar)
{
Foo foo = mapper.Map(bar);
//do stuff with foo
}
在初始配置调用 Map 方法后,我将在我的应用程序中做的所有事情。我不需要修改配置。我应该将 IMapper 实例还是 MapperConfiguration 实例存储在我的依赖注入(inject)容器中?
更新:我最终用我的 D.I. 注册了 IMapper。容器。就我而言,Unity。
最佳答案
我不明白你为什么不能同时存储两者。在某些情况下,我需要注入(inject)一个或另一个或两者,因为我使用 MapperConfiguration
进行 LINQ 投影,使用 IMapper
进行映射本身。我的 IoC 注册看起来像这样:
public static Container RegisterAutoMapper(this Container container)
{
var profiles = typeof(AutoMapperRegistry).Assembly.GetTypes().Where(t => typeof(Profile).IsAssignableFrom(t)).Select(t => (Profile)Activator.CreateInstance(t));
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
container.RegisterSingleton<MapperConfiguration>(() => config);
container.RegisterSingleton<IMapper>(() => container.GetInstance<MapperConfiguration>().CreateMapper());
return container;
}
因为 IMapper
对象可以通过 MapperConfiguration
创建,我的 IoC 正在从 的当前注册生成一个
。IMapper
实例映射器配置
关于c# - 迁移到 AutoMapper 4.2/5.0 时,我应该在依赖注入(inject)容器中存储 IMapper 实例还是 MapperConfiguration 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36619635/