如何在Ninject中使用AutoMApper.5.2.0?

时间:2016-12-02 17:36:00

标签: dependency-injection ninject automapper ninject.web.mvc

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

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

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

  1. 核心
  2. 数据
  3. 服务
  4. 网络
  5. 我在这个link处理同一个项目。

1 个答案:

答案 0 :(得分:7)

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

  1. Bind()AutoMapper.IMapper
  2. 指示AutoMapper将Ninject用于其服务,
  3. 使用您的映射初始化AutoMapper。
  4. 这是我用于此目的的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;
        }
    }
    

    然后您只需将AutoMapper.IMapper注入您的课程,而不是使用静态Mapper

相关问题