Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring the latest version of AutoMapper at the Global.asax level in an ASP.NET MVC Application

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?

like image 445
Blake Rivell Avatar asked Feb 06 '23 11:02

Blake Rivell


1 Answers

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

like image 90
IntoNET Avatar answered Feb 12 '23 12:02

IntoNET