I am currently migrating several mapping profiles from Automapper 4.2.1 to the latest version 9.0.0. The old mapping profiles are build up hierarchical, where the abstract base class requires an argument of type IDatetime
. This injection is used for testing only.
public abstract MappingProfileBase : Profile
{
protected MappingProfileBase(IDatetime datetime)
{
this.CreateMap<Foo, FooDto>()
.ForMember(dest => dest.SomeTimeStamp, opt => opt.MapFrom(src => datetime));
// Further mappings
}
}
public MappingProfileA : MappingProfileBase
{
public MappingProfileA(IDatetime datetime) : base(datetime)
{
this.CreateMap<FooDerived, FooDerivedDto>()
// Further and more specific mappings
}
}
Now I would like to move to the new Include
and IncludeBase<>
methods and undo the inheritance of MappingProfileA
and MappingProfileBase
but simply don't know how to deal with the injected interface. None of the new methods is taking any arguments.
This is how I think it should look like:
public class MappingProfileBase : Profile
{
public MappingProfileBase(IDatetime datetime)
{
this.CreateMap<Foo, FooDto>()
.ForMember(dest => dest.SomeTimeStamp, opt => opt.MapFrom(src => datetime));
// Further mappings
}
}
public class MappingProfileA : Profile
{
public MappingProfileA()
{
this.CreateMap<FooDerived, FooDerivedDto>();
.IncludeBase<Foo, FooDto>();
}
}
So how can I pass arguments to the constructor of the base class? What other possibilities do exist?
Thanks (again) to Lucian. I solved it by providing a profile instance to
AddProfile
(instead of aType
) using Autofac. I therefor had to register the concrete type beforehand to the container.Here are two example profiles:
And then from within a unit test:
Of course the static method
GetMappingConfiguration
requires further modification. But in principle it works.Using
IncludeBase
comes with the benefit of no code duplication. But on the other hand more complex profiles and test setup especially in this case.