Most of the examples I\'ve found for Automapper use the static Mapper object for managing type mappings. For my project, I need to inject an IMapperEngine as part of object
The static API will be removed in version 5.0.Use a MapperConfiguration instance and store statically as needed. Use CreateMapper to create a mapper instance.
in new version (4.2.0 >=) we should hold and pass IMapper through DI.
a simple Configure Service should be like this (ASP.NET Core)
services.AddSingleton(_ => new MapperConfiguration(cfg =>
{
cfg.CreateMap();
})
.CreateMapper());
and our service layer (with the help of constructor injection) :
public class CrudService : ICrudService
{
private readonly IMapper _internalMapper;
private readonly IRepository _repository;
public CrudService(IRepository repository, IMapper mapper)
{
_internalMapper = mapper;
_repository = repository;
}
public virtual ServiceResult Create(TModel foo)
{
var bar = _internalMapper.Map(foo);
try
{
_repository.Create(bar);
}
catch (Exception ex)
{
return ServiceResult.Exception(ex);
}
return ServiceResult.Okay(entity.Id);
}
}
consider TDocument as Bar, and TModel as Foo
update :
AutoMapper 4.2.1 released – Static is back
After a bit of feedback and soul searching and honestly tired of dealing with questions, some of the static API is restored in this release. You can now (and in the future) use Mapper.Initialize and Mapper.Map