代码之家  ›  专栏  ›  技术社区  ›  David Lay

如何将automapper配置为注入ninject 2.0?

  •  4
  • David Lay  · 技术社区  · 15 年前

    结构图和温莎的配置示例如下: http://www.cprieto.com/index.php/2009/08/20/using-automapper-with-castle-windsor/

    但我找不到任何适合Ninject的东西。

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

    2 回复  |  直到 13 年前
        1
  •  2
  •   Dana Benson    13 年前
    public class AutoMapperModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);
        }
    }
    
        2
  •  5
  •   Aaronaught    14 年前

    非常简单,只需加载此模块:

    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>();
        }
    }
    

    关于这一点需要注意的几点:

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

    • 自我约束的原因 配置 然后方法绑定 IConfiguration IConfigurationProvider 与温莎不同的是,Ninject不提供任何一级支持,将多个接口绑定到一个目标范围,因此这种黑客行为。

    这就是一切。使用依赖项编写容器类 形象塑造 (如果要创建新地图)和/或 IMappingEngine (实际进行映射),Ninject将毫无问题地注入它们。

    如果您想进行超松散耦合,并在自己的类中定义每个映射,那么您可能需要查看 Conventions Extension 对于ninject,它可以进行类似于windsor的汇编扫描 FromAssembly . 这也可以加载任何自定义 IObj-映射器 可以在单独的库中定义的类。