gpt4 book ai didi

asp.net-mvc-5 - 使用 Ninject 将参数注入(inject)自动映射器自定义 ValueResolver

转载 作者:行者123 更新时间:2023-12-01 18:12:47 26 4
gpt4 key购买 nike

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

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

在我的个人资料类中:

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

但是我收到此异常消息{“类型需要有一个带有 0 个参数或只有可选参数的构造函数\r\n参数名称:类型”}

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

关于asp.net-mvc-5 - 使用 Ninject 将参数注入(inject)自动映射器自定义 ValueResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com