解決策は 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-コードはいくつかのヘルパーと拡張機能を使用している可能性がありますが、コアのものはそこにあります.