Reputation: 13875
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?
Upvotes: 5
Views: 8648
Reputation: 13233
What you need to do is the following:
Mapper.Initialize(cfg =>
{
cfg.CreateMissingTypeMaps = true;
cfg.AddProfile<MappingProfile>();
});
This will configure the static mapper instance that was exposed in the old AutoMapper so that you can do:
Mapper.Map<SomeType>(fromObject);
If you don't want to use the static instance then you need to look at the IntoNET answer.
The "CreateMissingTypeMaps" line ensures that missing mappings are created "on the fly". It's the equivalent of the old:
Mapper.DynamicMap<SomeType>(fromObject)
If you want to define each mapping by hand you can remove this line.
There was a version of AutoMapper where author tried to get rid of the exposed static for some reason but he brought it back after public outcry from what I understand. So now you can do it any way you find suitable. You can read about it here:
Upvotes: 2
Reputation: 504
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
Upvotes: 7