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

When migrating to AutoMapper 4.2/5.0, should I store an IMapper instance or the MapperConfiguration instance in my dependency injection container?

我正在迁移到 newer configuration of AutoMapper. I was looking at examples on the 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 注册了 IMapper。容器。就我而言,Unity。

我不明白你为什么不能同时存储两者。在某些情况下,我需要注入一个或另一个或两者,因为我使用 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 实例。