Configuring AutoMapper v4.2 when starting an application without a static API

I am trying to move from the old static AutoMapper API to a new way of doing things according to this resource .

However, I'm a little confused about how I should configure AutoMapper in the file Startup.cs / Global.asax.

Old way to do something like this:

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

Then anywhere in the code, I could simply simply:

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

Now with the new version it seems that there is no way to initialize AutoMapper when the application starts, and then use it in the controller. The only way I understood how to do this is to do everything in the controller like this:

 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 need to configure AutoMapper every time I use it now in my MVC controllers or elsewhere in my application? Yes, the documentation shows you how to configure it in a new way, but they just set it on the config variable, which cannot work around my entire application.

I found this documentation on maintaining static. But I'm a little confused as to what MyApplication.Mapper is and where I should declare it. This is similar to a global application property.

+7
c # asp.net-mvc automapper
source share
1 answer

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 Application_Start from Global.asax, call the RegisterMapping method

 AutoMapperConfig.RegisterMappings(); 

3.) Create a map in your controller.

 IMapper Mapper = AutoMapperConfig.MapperConfiguration.CreateMapper(); Mapper.Map<Dest>(source); 
+10
source share

All Articles