AutoMapper与Ninject [英] AutoMapper with Ninject

查看:251
本文介绍了AutoMapper与Ninject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图安装AutoMapper通过Ninject实例的所有对象。
我有以下code在我的Global.asax文件

I've been trying to setup AutoMapper to instantiate all objects via Ninject. I've got the following code in my global.asax file

Mapper.Configuration.ConstructServicesUsing(x => kernel.Get(x));

和作为一个例子,我有以下映射

And as an example I have the following mapping

Mapper.CreateMap<TestModel, IndexViewModel>();

然而,这不会出现要工作。我得到一个错误IndexViewModel'没有默认构造函数。

However, this does not appear to be working. I get an error that 'IndexViewModel' does not have a default constructor.

我可以映射器通过明确地告诉automapper在映射使用ninject工作。

I can get the mapper to work by explicitly telling automapper to use ninject in the mapping.

Mapper.CreateMap<TestModel, IndexViewModel>().ConstructUsingServiceLocator();

不过,我宁愿没有为每一个映射做到这一点。我缺少的东西吗?

However, I'd rather not have to do this for every single mapping. Am I missing something?

推荐答案

只需创建一个函数来为你的地方在初始化code做到这一点。

Just create a function to do this for you somewhere in your initialisation code

void CreateMapWithServiceLocator<T1,T2>()
{
     Mapper.CreateMap<T1,T2>().ConstructUsingServiceLocator();
} 

这篇关于AutoMapper与Ninject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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