【问题标题】:Inject parameter into automapper custom ValueResolver using Ninject使用 Ninject 将参数注入 automapper 自定义 ValueResolver
【发布时间】:2014-07-08 01:29:16
【问题描述】:

我正在使用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"}

关于如何让 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));
        });
    }
}

【问题讨论】:

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


    【解决方案1】:

    您可以使用ConstructedBy 函数来配置Automapper 在调用ResolveUsing 后应该如何创建您的GetManagerResolver

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

    【讨论】:

    • 好,现在我怎样才能在我的自动映射器配置类中获得对kernel 的引用?查看我的问题更新
    • 第一:现在这是一个完全不同且未实现的问题...第二:有多种选择:将其作为参数传递给Configure 将您的内核存储在您创建它的静态字段中,等
    • 有人设法让 Ninject 使用 ConstructServicesUsing_ 吗?
    【解决方案2】:

    我最终做的是为Automapper 创建NinjectModule,我将所有自动映射器配置放在其中,并告诉自动映射器使用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());
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      相关资源
      最近更新 更多