如何在Ninject中使用AutoMApper.5.2.0?

Mor*_*orz 4 dependency-injection ninject automapper ninject.web.mvc

我现在正在开发一个大型ASP.NET MVC 5项目,我正在使用Ninject框架为MVC实现DI.实际上这是我第一次使用Ninject,我很难知道使用AutoMApper 5.2.0的最佳做法是什么.

在谷歌搜索之后,我发现了一些示例,这些示例演示了旧版本的AutoMapper,它在新版本中有一些不推荐使用的方法.

我的解决方案包括以下项目:

  1. 核心
  2. 数据
  3. 服务
  4. 卷筒纸

我正在这个链接中处理同一个项目.

dav*_*ben 7

在Ninject中需要为AutoMapper设置三件事.

  1. 绑定() AutoMapper.IMapper
  2. 指示AutoMapper将Ninject用于其服务,以及
  3. 使用映射初始化AutoMapper.

这是NinjectModule我用于此目的:

public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Bind<IMapper>().ToMethod(AutoMapper).InSingletonScope();
    }

    private IMapper AutoMapper(Ninject.Activation.IContext context)
    {
        Mapper.Initialize(config =>
        {
            config.ConstructServicesUsing(type => context.Kernel.Get(type));

            config.CreateMap<MySource, MyDest>();
            // .... other mappings, Profiles, etc.              

        });

        Mapper.AssertConfigurationIsValid(); // optional
        return Mapper.Instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你只需要注入AutoMapper.IMapper你的类而不是使用静态Mapper