Having AutoMapper to inject dependencies using an IoC Container when needed

陌路散爱 提交于 2019-12-14 04:07:17

问题


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

回答1:


Like this:

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

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



来源:https://stackoverflow.com/questions/24104798/having-automapper-to-inject-dependencies-using-an-ioc-container-when-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!