当迁移到AutoMapper 4.2/5.0时,我应该在依赖注入容器中存储一个IMapper实例还是MapperConfiguration实例?

3
我正在迁移到AutoMapper的新配置。我正在查看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实例?
更新:最终我使用我的D.I.容器(Unity)注册了IMapper。
1个回答

2

我认为你完全可以同时存储两者。我的情况是需要注入其中一个或两个,因为我使用 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正在从当前MapperConfiguration的注册中生成一个IMapper实例。


1
你使用的是哪个版本?这取决于,从版本4到版本5已经有所改变。有一些已弃用的内容和一些新的建议。 - alltej
@alltej,你能指出那些变化是什么吗?我正在尝试迁移到版本5。 - Shago
@james:为什么每次请求IMapper接口时都要创建一个新的Mapper实例?这样做是否会增加不必要的开销?在我看来,使用单例模式可能更好(既快速又节省内存)。 - Al Kepp
一个单例模式确实更合适,我会更新我的答案。 - James

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接