Automapper 4.2 Unity注入MapperConfiguration

时间:2016-02-12 13:24:42

标签: c# dependency-injection unity-container automapper-4

我无法想象如何将以下结构图实现转换为统一。

public AutoMapperRegistry()
{
    var profiles =
        from t in typeof (AutoMapperRegistry).Assembly.GetTypes()
        where typeof (Profile).IsAssignableFrom(t)
        select (Profile)Activator.CreateInstance(t);

    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });

    For<MapperConfiguration>().Use(config);
    For<IMapper>().Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));
}

2 个答案:

答案 0 :(得分:5)

遇到同样的问题,最后通过以下方式让它发挥作用

        var configuration = new MapperConfiguration(x =>
        {
              //Your configuration for your mapper
        });

        var mapper = configuration.CreateMapper();

        container.RegisterInstance(mapper);

答案 1 :(得分:0)

我最终使用了以下扩展方法

    public static IUnityContainer RegisterMapper(this IUnityContainer container)
    {
        return container
        .RegisterType<MapperConfiguration>(new ContainerControlledLifetimeManager(), new InjectionFactory(c =>
               new MapperConfiguration(configuration =>
               {
                   configuration.ConstructServicesUsing(t => container.Resolve(t));
                   foreach (var profile in c.ResolveAll<Profile>())
                       configuration.AddProfile(profile);
               })))
        .RegisterType<IConfigurationProvider>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => c.Resolve<MapperConfiguration>()))
        .RegisterType<IMapper>(new InjectionFactory(c => c.Resolve<MapperConfiguration>().CreateMapper()));
    }

    public static IUnityContainer RegisterMappingProfile<T>(this IUnityContainer container)
        where T : Profile
    {
        return RegisterMappingProfile(container, typeof(T));
    }

在我的Unity容器配置类中,我称之为

        container.RegisterMapper();
        container.RegisterMappingProfile<WebProfile>();