将服务注入到AutoMapper目标类中 [英] Inject service into an AutoMapper destination class

查看:156
本文介绍了将服务注入到AutoMapper目标类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个使用AutoMapper映射的源类和目标类. 目的地将记录器服务注入到构造函数中.

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

但是,我不知道如何通过StructureMap将服务注入到构造函数中?

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

我尝试了以下操作:

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.

我还尝试了以下方法:

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

但是我得到了一个错误:无法将Lamda表达式转换为委托类型,但是我看到的所有示例都使用此方法吗?

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

推荐答案

您传递给ConstructUsing的lambda必须返回目标类型的实例.因此,就您而言,您想这样做:

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

假设您正确设置了StructureMap,它将创建Dest对象并为您注入ILoggerService.

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

这篇关于将服务注入到AutoMapper目标类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆