Asp.net mvc 5 使用Ninject将参数注入automapper自定义ValueResolver
我正在使用Asp.net mvc 5 使用Ninject将参数注入automapper自定义ValueResolver,asp.net-mvc-5,ninject,automapper,Asp.net Mvc 5,Ninject,Automapper,我正在使用automapper库将我的Model转换为我的ViewModel。对于每个模型,我创建了配置文件,在其中我使用CreateMap添加了我的地图 我想使用自定义的ValueResolver,它将从IContext获取记录的用户ID,因此我需要使用Ninject传递IContext的实现 在我的个人资料类中: Mapper.CreateMap<ViewModel, BusinessModel>() .ForMember(dest => dest.ManagerId, o
automapper
库将我的Model
转换为我的ViewModel
。对于每个模型
,我创建了配置文件,在其中我使用CreateMap
添加了我的地图
我想使用自定义的ValueResolver
,它将从IContext
获取记录的用户ID,因此我需要使用Ninject传递IContext
的实现
在我的个人资料类中:
Mapper.CreateMap<ViewModel, BusinessModel>()
.ForMember(dest => dest.ManagerId, opt => opt.ResolveUsing<GetManagerResolver>());
但是我得到了这个异常消息{“Type需要有一个包含0个参数的构造函数,或者只有可选的参数\r\n参数名:Type”}
关于如何让automapper使用ninject创建对象有什么想法吗
更新
添加自动映射配置的我的代码:
public static class AutoMapperWebConfiguration
{
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile(new Profile1());
cfg.AddProfile(new Profile2());
// now i want to add this line, but how to get access to kernel in static class?
// cfg.ConstructServicesUsing(t => Kernel.Get(t));
});
}
}
您可以使用
ConstructedBy
函数来配置Automapper在调用ResolveUsing
后如何创建GetManagerResolver
:
Mapper.CreateMap()
.ForMember(dest=>dest.ManagerId,
opt=>opt.resolvesusing()
.ConstructedBy(()=>kernel.Get());
或者,当使用Mapper.Configuration.ConstructServicesUsing
方法解析任何类型时,您可以全局单独指定Automapper使用的Ninject内核:
Mapper.Configuration.ConstructServicesUsing((type)=>kernel.Get(type));
我最后做的是为Automapper
创建NinjectModule
,在那里我放置了所有Automapper配置,并告诉Automapper使用Ninject内核构建对象。下面是我的代码:
public class AutoMapperModule : NinjectModule
{
public override void Load()
{
Mapper.Initialize(cfg =>
{
cfg.ConstructServicesUsing(t => Kernel.Get(t));
cfg.AddProfile(new Profile1());
cfg.AddProfile(new Profile2());
});
}
}
很好,现在我如何在我的automapper配置类中获得对内核的引用?请参阅我的问题更新第一:这现在是一个完全不同的未解决的问题…第二:有多个选项:将其作为参数传递到配置将内核存储在创建它的静态字段中,等等。有人年龄大了,可以在施工服务中工作吗?
public class AutoMapperModule : NinjectModule
{
public override void Load()
{
Mapper.Initialize(cfg =>
{
cfg.ConstructServicesUsing(t => Kernel.Get(t));
cfg.AddProfile(new Profile1());
cfg.AddProfile(new Profile2());
});
}
}