【问题标题】:Create map with DBContext lookup, using automapper and ninject使用自动映射器和 ninject 使用 DBContext 查找创建地图
【发布时间】:2014-08-18 11:22:19
【问题描述】:

所以我想做的是使用我的 DBContext 从数据库中获取一些信息以进行映射。

所以我创建了一个自定义的 TypeConverter:

public class RoundVMtoTrampetRound : ITypeConverter<RoundVM, TrampetRound>
{

    public RoundVMtoTrampetRound(DBTariff context)
    {
        this.context = context;
    }

    private DBTariff context { get; set; }

    public TrampetRound Convert(ResolutionContext context)
    {
        RoundVM source = (RoundVM)context.SourceValue;
        Mapper.CreateMap<RoundVM, TrampetRound>();
        var dest = Mapper.Map<TrampetRound>(source);
        dest.Difficulty = this.context.DifficultyTrampet.Find(source.Id);
        return dest;
    }
}

在我的控制器中,我使用以下方法创建了一个映射器:

Mapper.CreateMap<RoundVM, TrampetRound>().ConvertUsing<RoundVMtoTrampetRound>();

但是当我进行映射时,我收到错误消息说没有默认构造函数。但我希望 ninject 使用代码为我执行此操作:

kernel.Bind<DBTariff>().ToSelf().InRequestScope();

答案在这里,但我仍然遇到同样的问题 Automapper + EF4 + ASP.NET MVC - getting 'context disposed' error (I know why, but how to fix it?)

我已经尝试了链接中给出的解决方案,但得到了同样的错误。 那么如何让 Automapper 使用我的 Ninject 来解决问题呢?

编辑

我还发现这个用 autofac 完成了同样的事情 http://thoai-nguyen.blogspot.se/2011/10/autofac-automapper-custom-converter-di.html 所以我的猜测是我需要告诉 automapper 使用我的 ninject 解析器,但我该怎么做以及在哪里做?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework ninject automapper


    【解决方案1】:

    您需要的所有信息都在blog article you already linked 中提供。 要将其分解为绝对最少的信息,您需要这样做:

    Mapper.Initialize(x =>
    {
         x.ConstructServicesUsing(type => kernel.Get(type));
    });
    

    在您访问任何其他Mapper. 属性/方法之前,因此您需要先调用Mapper.Initialize(..),然后再调用Mapper.CreateMap

    【讨论】:

    • 谢谢,但我应该把这个放在哪里?在 NinjectWebCommon 中还是在每个控制器中?
    • 我对 .net MVC 的东西并不十分熟悉,但我很确定将其放入每个控制器会破坏“在 Mapper.CreateMap! Ideally you'd put it immediately after the new StandardKernel() 之前初始化”语句。现在,由于这可能由一些 ninject nuget 包处理,您必须检查 NinjectWebCommon 的扩展点类型。您可以尝试将其放入 NinjectHttpApplication.CreateKernel() 的覆盖中
    • new StandardKernel() 在 NinjectWebCommon 中并且可以正常工作!谢谢!
    猜你喜欢
    • 2021-06-11
    • 2017-01-08
    • 1970-01-01
    • 2021-10-28
    • 2015-12-13
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多