简体   繁体   中英

Automapper 4.2 Unity Inject MapperConfiguration

I can't quite figure how to convert the following structure map implementation to unity.

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));
}

Ran across the same issue, finally got it working by doing the following

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

        var mapper = configuration.CreateMapper();

        container.RegisterInstance(mapper);

I ended up using the following extension methods

    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()));
    }

and

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

In my unity container config class I call them

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM