AutoMapper与Ninject(AutoMapper with Ninject)

2019-09-17 04:27发布

我一直在试图建立AutoMapper通过Ninject实例的所有对象。 我有下面的代码在我的Global.asax文件

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

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

Mapper.CreateMap<TestModel, IndexViewModel>();

然而,这似乎并不奏效。 我得到一个错误“IndexViewModel”没有默认构造函数。

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

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

但是,我宁愿不必为每一个映射做到这一点。 我缺少的东西吗?

Answer 1:

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

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


文章来源: AutoMapper with Ninject