Inject service into an AutoMapper destination class

萝らか妹 提交于 2020-01-13 08:40:07

问题


Say I have a source and destination class that is mapped using AutoMapper. The destination has a logger service injected into the constructor.

However, I don't know how to get the service injected into the constructor through StructureMap?

I've tried the following:

Mapper.Initialize(m =>
 {                
    m.ConstructServicesUsing(ObjectFactory.GetInstance);
 });

which didn't prevent me having the exception on the mapping call, I guess because the service isn't being injected in properly.

I also tried the following:

CreateMap<Source, Dest>()
 .ConstructUsing(x=> ObjectFactory.GetInstance<ILoggerService>());

But I get the error: cannot convert Lamda expression to delegate type, yet all the examples I have seen use this method?


回答1:


The lambda you pass into ConstructUsing must return an instance of the destination type. So in your case, you would want to do this:

CreateMap<Source, Dest>()  
.ConstructUsing(x=> ObjectFactory.GetInstance<Dest>());

Assuming you have StructureMap setup correctly, it should create the Dest object and inject the ILoggerService for you.




回答2:


You can also do this:

        Mapper.Configuration.ConstructServicesUsing(container.Resolve);

        Mapper.CreateMap<Source, Dest>().ConstructUsingServiceLocator();


来源:https://stackoverflow.com/questions/5938704/inject-service-into-an-automapper-destination-class

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