4

現在、AutoMapper (最新の .NET 3.5 バージョン) を試しています。AutoMapper を機能させるには、あるオブジェクトから別のオブジェクトにマップする方法に関する構成の詳細を AutoMapper に提供する必要があります。

Mapper.CreateMap<ContactDTO, Contact>();
Mapper.CreateMap<Contact, ContactDTO>();

アプリケーション、サービス、Web サイトの開始時にこれを行う必要があります。(global.asax などを使用)

問題は、GAC の DLL で Automapper を使用して、LINQ2SQL オブジェクトを対応する BO にマップしていることです。常に .CreateMap<> の詳細を指定する必要がないようにするには、マップ 2 オブジェクトが必要ですが、可能であれば、この構成をどこで指定できますか?

4

1 に答える 1

0

解決策は AutoMapper 自体にあると思います。

AutoMapper プロファイルを使用して、起動時に登録します。

以下の例では、プロファイルが依存関係を必要としない場合、IOC コンテナーは必要ありません。

/// <summary>
///     Helper class for scanning assemblies and automatically adding AutoMapper.Profile
///     implementations to the AutoMapper Configuration.
/// </summary>
public static class AutoProfiler
{
    public static void RegisterReferencedProfiles()
    {
        AppDomain.CurrentDomain
            .GetReferencedTypes()
            .Where(type => type != typeof(Profile) 
              && typeof(Profile).IsAssignableFrom(type) 
              && !type.IsAbstract)
            .ForEach(type => Mapper.Configuration.AddProfile(
              (Profile)Activator.CreateInstance(type)));
    }
}

そして、この例のようにプロファイルを実装するだけです:

public class ContactMappingProfile : Profile
{
    protected override void Configure()
    {
        this.CreateMap<Contact, ContactDTO>();
        this.CreateMap<ContactDTO, Contact>();
    }
}

ただし、プロファイルに解決する必要がある依存関係がある場合は、AutoMapper の抽象化を作成し、抽象化を登録する直前にすべてのプロファイルを登録することができます - IObjectMapper - 次のようなシングルトンとして:

public class AutoMapperModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        base.Load(builder);

        // register all profiles in container
        AppDomain.CurrentDomain
            .GetReferencedTypes()
            .Where(type => type != typeof(Profile)
              && typeof(Profile).IsAssignableFrom(type) 
              && !type.IsAbstract)
            .ForEach(type => builder
                .RegisterType(type)
                .As<Profile>()
                .PropertiesAutowired());

        // register mapper
        builder
            .Register(
                context =>
                {
                    // register all profiles in AutoMapper
                    context
                        .Resolve<IEnumerable<Profile>>()
                        .ForEach(Mapper.Configuration.AddProfile);
                    // register object mapper implementation
                    return new AutoMapperObjectMapper();
                })
            .As<IObjectMapper>()
            .SingleInstance()
            .AutoActivate();
    }
}

私はドメイン内のすべての技術を抽象化しているので、これが私にとって最良のアプローチのように思えました。

さあ、コードを書いてみよう、おい!

PS-コードはいくつかのヘルパーと拡張機能を使用している可能性がありますが、コアのものはそこにあります.

于 2015-02-08T16:03:46.130 に答える