10

Ninject を使用して AutoMapper を ASP.NET MVC 2 アプリケーションに挿入するのに問題があります。AutoMapper および StructureMap タイプの構成に関する Jimmy Bogard の投稿をガイドとして使用しました。

public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Bind<ITypeMapFactory>().To<TypeMapFactory>();
        Bind<Configuration>().ToSelf().InSingletonScope().WithConstructorArgument("mapper", MapperRegistry.AllMappers);
        Bind<IConfiguration>().To<Configuration>();
        Bind<IConfigurationProvider>().To<Configuration>();
        Bind<IMappingEngine>().To<MappingEngine>();
    }
}

Ninject は、解決時に例外をスローしますConfiguration

IObjectMapper のアクティブ化でエラーが発生しました 一致するバインディングが利用できず、型が自己バインド可能ではありません。アクティベーション パス:
3) Configuration 型のコンストラクターのパラメーター マッパーへの依存関係 IObjectMapper の注入

アップデート

これは現在、次のバインディングを使用して機能しています。

    Bind<ITypeMapFactory>().To<TypeMapFactory>();
    Bind<Configuration>().ToConstant(new Configuration(Kernel.Get<ITypeMapFactory>(), MapperRegistry.AllMappers())).InSingletonScope();
    Bind<IConfiguration>().ToMethod(c => c.Kernel.Get<Configuration>());
    Bind<IConfigurationProvider>().ToMethod(c => c.Kernel.Get<Configuration>());
    Bind<IMappingEngine>().To<MappingEngine>();

モジュールを GitHub に公開しました。AutoMapper.Ninject . 私のブログの詳細: http://binaryspeakeasy.com/2010/09/automapper-ninject/

4

3 に答える 3

11

これは、最新バージョン (現在 2.2.0) を使用したワンライナーで実行できます。

kernel.Rebind<IMappingEngine>().ToMethod(context => Mapper.Engine);

さらに、私は fodonnel に同意します。ファサードを追加して Automapper インターフェイスを非表示にすることは良い考えですが、すべての機能が必要でない限り、Automapper から署名を直接取得することはありません。

于 2012-10-11T14:55:05.810 に答える
2

マッピングファサードを導入することも良い考えかもしれません。コード全体にIMappingEngineを渡す代わりに、IObjectMapperインターフェイスを作成します。私が使用するインターフェースには、オートマッパーコードから直接取得したメソッドシグネチャが含まれています。

public interface IObjectMapper
{ 
  TDestination Map(TSource source);
  TDestination Map(TSource source, TDestination destination);
  object Map(object source, Type sourceType, Type destinationType);
  object Map(object source, object destination, Type sourceType, Type destinationType);
}

構成は引き続きオートマッパーに依存します。

私が書いたブログ投稿はここにあります:http://fodonnel.wordpress.com/2010/09/20/an-object-mapper-facade/

于 2010-09-20T12:19:54.373 に答える
1

うまくいきましたが、構成クラスのインスタンスを作成するのはあまりきれいではありません。さらにクリーンアップするための提案。

        Bind<ITypeMapFactory>().To<TypeMapFactory>();
        Bind<Configuration>().ToConstant(new Configuration(Kernel.Get<ITypeMapFactory>(), MapperRegistry.AllMappers())).InSingletonScope();
        Bind<IConfiguration>().ToMethod(c => c.Kernel.Get<Configuration>());
        Bind<IConfigurationProvider>().ToMethod(c => c.Kernel.Get<Configuration>());
        Bind<IMappingEngine>().To<MappingEngine>();
于 2010-09-02T05:15:07.473 に答える