I had defined in my project a global Automapper configuration that would allow me to use Mapper.Map in my code. (See my configu
This is how I've handled it.
Create maps in a Profile, taking care to use the Profile's CreateMap method rather than Mapper's static method of the same name:
internal class MappingProfile : Profile
{
protected override void Configure()
{
CreateMap();
}
}
Then, wherever dependencies are wired-up (ex: Global.asax or Startup), create a MapperConfiguration and then use it to create an IMapper.
var mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingProfile());
});
Then, use the configuration to generate an IMapper:
var mapper = mapperConfiguration.CreateMapper();
Then, register that mapper with the dependency builder (I'm using Autofac here)
builder.RegisterInstance(mapper).As();
Now, wherever you need to map stuff, declare a dependency on IMapper:
internal class ProjectService : IProjectService {
private readonly IMapper _mapper;
public ProjectService(IMapper mapper) {
_mapper = mapper;
}
public ProjectCreate Get(string key) {
var project = GetProjectSomehow(key);
return _mapper.Map(project);
}
}