8

1 つの大きな AutoMapperConfiguration クラスの使用から実際のプロファイルの使用に AutoMappers をロールオーバーしています。グローバルはそのようになりました (今のところ、Open/Close 違反を許してください)

Mapper.Initialize(x =>
                       {
                          x.AddProfile<ABCMappingProfile>();
                          x.AddProfile<XYZMappingProfile>();
                          // etc., etc.
                  });

私を最高の状態に導いた重要な要素であり、以前は常にプロファイルの使用を妨げていたハードルは、私の ninject バインディングでした。バインディングを機能させることができませんでした。以前はこのバインディングがありました:

Bind<IMappingEngine>().ToConstant(Mapper.Engine).InSingletonScope();

それ以来、私はこのバインディングに移行しました:

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

これは機能し、アプリは機能し、プロファイルがあり、状況は良好です。

ヒッチは現在、私の単体テストにあります。NUnit を使用して、コンストラクターの依存関係をセットアップします。

private readonly IMappingEngine _mappingEngine = Mapper.Engine;

[Setup] メソッドで MVC コントローラーを作成し、AutoMapperConfiguration クラスを呼び出します。

[SetUp]
public void Setup()
{
    _apiController = new ApiController(_mappingEngine);
    AutoMapperConfiguration.Configure();
}

私は今に変更しました。

[SetUp]
public void Setup()
{
    _apiController = new ApiController(_mappingEngine);

    Mapper.Initialize(x =>
                          {
                              x.AddProfile<ABCMappingProfile>();
                              x.AddProfile<XYZMappingProfile>();
                              // etc., etc.
                          });
}

残念ながら、これはうまくいかないようです。マッピングを使用するメソッドをヒットすると、AutoMapper がマッピングが存在しないことを示す例外をスローするため、マッピングが取得されていないようです。これを解決するために、テストでマッパーの定義/注入をどのように/何を変更するかについての提案はありますか? IMappingEngine フィールドの定義が問題だと思いますが、どのようなオプションがあるかわかりません。

ありがとう

4

1 に答える 1

3

Mapper.Engineあなたが抱えている問題は、AutoMapper の構成を含むある種のシングルトンであるstatic を使用した結果です。慣例により、Mapper.Engine設定後は変更しないでください。したがって、unittest ごとに提供して Automapper を構成するAutoMapper.Profiler場合は、使用を避ける必要があります。

変更は非常に簡単です:グローバルな static を使用する代わりに、クラスAutoMapperConfigurationを独自のインスタンスとしてインスタンス化します。AutoMapper.MappingEngineMapper.Engine

public class AutoMapperConfiguration 
{
    private volatile bool _isMappinginitialized;
    // now AutoMapperConfiguration  contains its own engine instance
    private MappingEngine _mappingEngine;

    private void Configure()
    {
        var configStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());

        configStore.AddProfile(new ABCMappingProfile());
        configStore.AddProfile(new XYZMappingProfile());

        _mappingEngine = new MappingEngine(configStore);

        _isMappinginitialized = true;
    }

    /* other methods */
}

ps:完全なサンプルはこちら

于 2013-04-24T04:04:29.200 に答える