I am using Automapper 5.2. I have used as a basis this link. I will describe, in steps, the process of setting up Automapper that I went through.
First
Starting with V9.0 of autoMapper, the static API is no longer available. or you can change version to 6.2.2 from NuGet Package Manager See this doc confgiration AutoMapper
Better Solution would be to create extension method like this
public static DestinationType CastObject<SourceType, DestinationType>(this SourceType obj)
{
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<SourceType, DestinationType>());
var mapper = config.CreateMapper();
var entity = mapper.Map<DestinationType>(obj);
return entity;
}
AutoMapper has two usages: dependency injection and the older static for backwards compatibility. You're configuring it for dependency injection, but then attempting to use the static. That's your issue. You just need to choose one method or the other and go with that.
If you want to do it with dependency injection, your controller should take the mapper as a constructor argument saving it to a member, and then you'll need to use that member to do your mapping:
public class FooController : Controller
{
private readonly IMapper mapper;
public FooController(IMapper mapper)
{
this.mapper = mapper;
}
Then:
IEnumerable<ClientViewModel> _clientVM = mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);
For the static method, you need to initialize AutoMapper with your config:
public MapperConfiguration Configure()
{
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.AddProfile<ViewModelToDomainMappingProfile>();
cfg.AddProfile<DomainToViewModelMappingProfile>();
cfg.AddProfile<BiDirectionalViewModelDomain>();
});
}
You then need only call this method in Startup.cs; you would no longer register the singleton.