使用Ninject将参数注入到automaticpper自定义ValueResolver中

时间:2014-06-30 15:53:41

标签: asp.net-mvc-5 ninject automapper

我正在使用automapper库将Model转换为我的ViewModel。对于每个Model,我创建了一个配置文件,我在其中使用CreateMap添加我的地图。

我想使用自定义ValueResolver,它将从IContext获取已记录的用户ID,因此我需要使用Ninject传递IContext的实现。

在我的个人资料类中:

Mapper.CreateMap<ViewModel, BusinessModel>()
.ForMember(dest => dest.ManagerId, opt => opt.ResolveUsing<GetManagerResolver>());

然后是我的GetManagerResolver

public class GetManagerResolver : ValueResolver<BusinessModel, int>
{
    private IContext context;
    public GetManagerResolver(IContext context)
    {
        this.context = context;
    }

    protected override int GetManagerResolver(BusinessModel source)
    {
        return context.UserId;
    }
}

但我收到此异常消息{"Type needs to have a constructor with 0 args or only optional args\r\nParameter name: type"}

关于make automapper如何使用ninject进行对象创建的任何想法?

更新 我的代码添加了automaticpper配置:

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

2 个答案:

答案 0 :(得分:8)

您可以使用ConstructedBy功能配置Automapper在致电GetManagerResolver后创建ResolveUsing的方式:

Mapper.CreateMap<ViewModel, BusinessModel>()
    .ForMember(dest => dest.ManagerId, 
         opt => opt.ResolveUsing<GetManagerResolver>()
                   .ConstructedBy(() => kernel.Get<GetManagerResolver>());

或者,您可以在使用Mapper.Configuration.ConstructServicesUsing方法解析任何类型时全局指定要由Automapper使用的Ninject内核:

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

答案 1 :(得分:3)

我最终做的是为NinjectModule创建Automapper,我在其中放置了所有的automapper配置,并告诉automapper使用Ninject Kernel来构造对象。这是我的代码:

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());
        });
    }
}
相关问题