Automapper 4.2 Unity Inject MapperConfiguration

2.1k Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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>();
3
On

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