Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring AutoMapper v4.2 on application start without the Static API

I am attempting to migrate from the old static AutoMapper API to the new way of doing things as per this resource.

However, I am a bit confused as to how I should be configuring AutoMapper in a file like Startup.cs/Global.asax.

The old way to do something like this was:

Mapper.Initialize(cfg => {
  cfg.CreateMap<Source, Dest>();
});

Then anywhere throughout the code I could simply just do:

var dest = Mapper.Map<Source, Dest>(source);

Now with the new version it seems that there is no way to initialize AutoMapper on Application Start and then use it in the Controller. The only way I have figured out how to do it is doing everything in the controller like so:

var config = new MapperConfiguration(cfg => {
  cfg.CreateMap<Source, Dest>();
});

IMapper mapper = config.CreateMapper();
var source = new Source();
var dest = mapper.Map<Source, Dest>(source);

Do I really have to configure AutoMapper every single time I use it now in my MVC controllers or anywhere else in my application? Yes, the documentation shows you how to configure it the new way, but they are just setting it to a variable called config which can't work around my entire app.

I found this documentation on keeping the static feel. But I am a bit confused as to what MyApplication.Mapper is and where I should declare it. It seems like a global application property.

like image 379
Blake Rivell Avatar asked Feb 13 '16 12:02

Blake Rivell


1 Answers

You could do something like this.
1.) Create a static class that has an attribute of type MapperConfiguration

public static class AutoMapperConfig
{
    public static MapperConfiguration MapperConfiguration;

    public static void RegisterMappings()
    {
        MapperConfiguration = new MapperConfiguration(cfg => {
            cfg.CreateMap<Source, Dest>().ReverseMap();
        });
    }
}

2.) In the Application_Start of Global.asax, call the RegisterMapping method

AutoMapperConfig.RegisterMappings();

3.) In your controller, create the mapper.

IMapper Mapper = AutoMapperConfig.MapperConfiguration.CreateMapper();
Mapper.Map<Dest>(source);
like image 170
Paul Sohal Avatar answered Oct 05 '22 05:10

Paul Sohal