Search code examples
inversion-of-controlunity-containerautomapperconstructor-injection

Having AutoMapper to inject dependencies using an IoC Container when needed


I have tried almost everything, but I cannot get AutoMapper to map A => B when B doesn't have a parameterless constructor.

I'm using Unity and all the dependencies are registered conveniently but, how do I say to AutoMapper "hey, if the target instance needs some dependency in the constructor, ask Unity to build it, and do the mapping later.

I've tried with

 Mapper.Initialize(configuration =>
        {
            configuration.ConstructServicesUsing(container.Resolve);
            configuration.CreateMap<Person, PersonViewModel>();
        });

But it doesn't work :(

EDIT: In fact, I lied a bit. I'm not using Unity. I'm using Grace, but didn't want to come up with a relatively unknown container asking about advances topics :)

I've solved the problem and it works as smooth as silk. The exact code is like this. Keep in mind that I'm using the Grace IoC Container (which I eagerly recommend).

Bootstrapper.Instance.Configure(new CompositionRoot());

        Mapper.Configuration.ConstructServicesUsing(type => Bootstrapper.Instance.Container.Locate(type));
        Mapper.CreateMap<Person, PersonViewModel>()
            .ConstructUsingServiceLocator();

Solution

  • Like this:

    configuration.CreateMap<Person, PersonViewModel>()
        .ConstructUsingServiceLocator();
    

    Do this for each mapping that should be created by your service locator.