4

MVCでコントローラーを作成する場合、追加の登録を行う必要はありません。エリアの追加についても同じことが言えます。global.asaxにAreaRegistration.RegisterAllAreas()呼び出しがある限り、追加の設定は必要ありません。

AutoMapperでは、ある種のCreateMap<TSource, TDestination>呼び出しを使用してマッピングを登録する必要があります。これらは、staticを使用して明示的に行うMapper.CreateMapか、クラスから派生しAutoMapper.Profile、メソッドをオーバーライドして、そこからConfigure呼び出すことで実行できCreateMapます。

Profileから拡張するクラスのMVCスキャンのように、から拡張するクラスのアセンブリをスキャンできるはずだと私には思えますController。このようなメカニズムでは、Profile?から派生したクラスを作成するだけでマッピングを作成できるのではないでしょうか。そのようなライブラリツールは存在しますか、それともオートマッパーに組み込まれているものがありますか?

4

2 に答える 2

9

そのようなツールが存在するかどうかはわかりませんが、ツールを作成するのは非常に簡単です。

public static class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x => GetConfiguration(Mapper.Configuration));
    }

    private static void GetConfiguration(IConfiguration configuration)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (var assembly in assemblies)
        {
            var profiles = assembly.GetTypes().Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x));
            foreach (var profile in profiles)
            {
                configuration.AddProfile((Profile)Activator.CreateInstance(profile));
            }
        }
    }
}

そして、あなたの中であなたは自動配線するApplication_Startことができます:

AutoMapperConfiguration.Configure();
于 2012-07-30T15:18:45.357 に答える
2

@Darin Dimitrovからの回答に対するわずかな改善として、AutoMapper 5では、次のようにスキャンするアセンブリのリストを指定できます。

//--As of 2016-09-22, AutoMapper blows up if you give it dynamic assemblies
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                    .Where(x => !x.IsDynamic);
//--AutoMapper will find all of the classes that extend Profile and will add them automatically    
Mapper.Initialize(cfg => cfg.AddProfiles(assemblies));
于 2016-09-22T20:29:49.827 に答える