我一直在尝试设置 AutoMapper 以通过 Ninject 实例化所有对象。 我的 global.asax 文件中有以下代码
Mapper.Configuration.ConstructServicesUsing(x => kernel.Get(x));
作为示例,我有以下映射
Mapper.CreateMap<TestModel, IndexViewModel>();
但是,这似乎不起作用。我收到“IndexViewModel”没有默认构造函数的错误。
我可以通过显式告诉 automapper 在映射中使用 ninject 来让映射器工作。
Mapper.CreateMap<TestModel, IndexViewModel>().ConstructUsingServiceLocator();
但是,我宁愿不必为每个映射都执行此操作。我错过了什么吗?
最佳答案
只需在初始化代码的某处创建一个函数来为您执行此操作
void CreateMapWithServiceLocator<T1,T2>()
{
Mapper.CreateMap<T1,T2>().ConstructUsingServiceLocator();
}
关于c# - AutoMapper 与 Ninject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10559026/