依赖注入 – 如何使用Ninject使用AutoMApper.5.2.0?

前端之家收集整理的这篇文章主要介绍了依赖注入 – 如何使用Ninject使用AutoMApper.5.2.0?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_2@
我现在正在开发一个大型ASP.NET MVC 5项目,我正在使用Ninject框架为MVC实现DI.实际上这是我第一次使用Ninject,我很难知道使用AutoMApper 5.2.0的最佳做法是什么.

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

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

>核心
>数据
>服务
>网络

我正在研究link中的同一个项目.

解决方法

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

> Bind()AutoMapper.IMapper
>指示AutoMapper将Ninject用于其服务,以及
>使用映射初始化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;
    }
}

那么你只需将AutoMapper.IMapper注入到类中,而不是使用静态Mapper

@H_403_2@

猜你在找的设计模式相关文章