如何配置要使用Ninject 2.0注入的Automapper?

Dav*_*Lay 4 .net ninject automapper

Structure Map和Windsor有一些配置示例:http: //www.cprieto.com/index.php/2009/08/20/using-automapper-with-castle-windsor/

但我没有为Ninject找到任何东西.

你知道如何将这些映射转换为Ninject吗?

Aar*_*ght 5

这真的很容易,只需加载这个模块:

public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Bind<ITypeMapFactory>().To<TypeMapFactory>();
        foreach (var mapper in MapperRegistry.AllMappers())
            Bind<IObjectMapper>().ToConstant(mapper);
        Bind<Configuration>().ToSelf().InSingletonScope()
            .WithConstructorArgument("mappers",
                ctx => ctx.Kernel.GetAll<IObjectMapper>());
        Bind<IConfiguration>().ToMethod(ctx => ctx.Kernel.Get<Configuration>());
        Bind<IConfigurationProvider>().ToMethod(ctx => 
            ctx.Kernel.Get<Configuration>());
        Bind<IMappingEngine>().To<MappingEngine>();
    }
}
Run Code Online (Sandbox Code Playgroud)

关于这个的一些注意事项:

  • 它不是仅仅MapperRegistry.AllMappers作为构造函数参数提供Configuration,而是实际上绑定每个人IObjectMapper,然后使用内核本身来获取WithConstructorArgument绑定中的构造函数参数.这样做的原因是,IObjectMapper如果您决定编写自己的自定义映射器,则可以将自己的绑定加载到内核​​中.

  • 其原因自粘合Configuration,然后方法结合IConfigurationIConfigurationProvider是不像温莎,Ninject不提供多个接口结合到单个目标范围,因此,本hack任何一流的支持.

这就是它的全部内容.使用依赖项编写容器类IConfiguration(如果要创建新映射)和/或IMappingEngine(实际执行映射),Ninject会毫无问题地注入它们.

如果你想进行超松散耦合并在其自己的类中定义每个映射,那么你可能想看看Ninject 的Conventions Extension,它可以进行类似于Windsor的汇编扫描FromAssembly.这也可以加载IObjectMapper您可能在单独的库中定义的任何自定义类.