I'm using ASP.net Core with AutoMapper. To get the DI running, I use the AutoMapper.Extensions.Microsoft.DependencyInjection Nuget-Package and let AutoMapper register the profiles via
private static void InitializeAutoMapper(IServiceCollection services)
{
services.AddAutoMapper();
}
This works fine, but for some Profiles, I'd like to inject also some dependencies to them, for example:
public class IndividualDtoProfile : Profile
{
private readonly IIndividualFactory _individualFactory;
private readonly IMapper _mapper;
public IndividualDtoProfile(IIndividualFactory individualFactory, IMapper mapper)
{
_individualFactory = individualFactory;
_mapper = mapper;
}
public IndividualDtoProfile()
{
CreateMap<Individual, IndividualDto>();
CreateMap<IndividualDto, Individual>()
.ConstructUsing(
dto =>
{
var gender = _mapper.Map<IndividualGender>(dto.Gender);
return _individualFactory.CreateIndividual(dto.FirstName, dto.LastName, gender, dto.BirthDate);
});
}
}
The only relevant discussion I found is here : https://groups.google.com/forum/#!topic/automapper-users/5XK7pqGu_Tg
Which pretty much seems to suggest to not use the goodness of the existing possibilities, but manually map the Profiles. The only other possibility I'd see is to provide a static ServiceProvider-Singleton, which also doesn't seem too appealing.
Is there already a possibility, to use ASP.Net Core with AutoMapper and let dependencies inject into Profiles?
Edit: Due to the comment, probably I'm also something fundamentally wrong: I'm learning Domain Driven Design, where I have an application layer. I'd like to map the DTOs, which are used from a Web-Service, back to the domain entities, and I assumed, it would make sense to use the Factories there too, since otherwise I would bypass the logic in the Factories.
IMapperinside a profile??! The profiles are used to add registrations, before the mapper is ready to be used (i.e. to perform a validation viaMapper.AssertConfigurationIsValid()). While I generally prefer to inject IMapper anywhere too, there are some limitations though. Are you using Automapper's EF projections? They don't work easily with injections, since the.ProjectTo()method uses the staticMapperclass insteadIndividualis an EF/EF Core Poco, in which case: never map from Dto to Persistence or Domain Models, it will bite you really hard (EF Core works with references, mapping this way may break the way how EF Core handles the entities, especially on collections)