I am trying to figure out how to configure the new AutoMapper at the Global.asax level.
I used to do the following with old AutoMapper:
Create a class in App_Start folder called MappingProfile.cs and in the constructor I would add my mappings like this:
public MappingProfile()
{
Mapper.CreateMap<Product, ProductDto>();
Mapper.CreateMap<ApplicationUser, UserDto>();
}
Then in Global.asax call:
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
Can someone please tell me how to achieve the above with the new version of AutoMapper? I have been reading the docs but can't seem to get it.
I believe I do something like this in my MappingProfile.cs file:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductDto>();
cfg.CreateMap<ApplicationUser, UserDto>();
});
but what do I do with the config variable?
This is how I do it.
public abstract class AutoMapperBase
{
protected readonly IMapper _mapper;
protected AutoMapperBase()
{
var config = new MapperConfiguration(x =>
{
x.CreateMap<Product, ProductDto>();
x.CreateMap<ApplicationUser, UserDto>();
});
_mapper = config.CreateMapper();
}
}
Then inherit AutoMapperBase from any class which needs to use it, and call it like this:
var foo = _mapper.Map<ProductDto>(someProduct);
You no longer need it declared or configured in Global.asax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With