How to use Automapper with a single dependency injection?

I plan to use Automapper with ASP.NET MVC and Unity DI. The video posted on automapper on how to use is very old and does not show how you can use mapper with dependency injection. Most stackoverflow examples also use the Mapper.CreateMap () method, which is now deprecated.

The automation manual says

Once you have your types, you can create a map for two types using an instance of MapperConfiguration and CreateMap. You only need one MapperConfiguration instance, usually for the AppDomain, and must be created at startup.

var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>()); 

So, I assume that the above line of code will go into launching the application, for example global.asax

To perform the mapping, create an IMapper using the CreateMapper method.

  var mapper = config.CreateMapper(); OrderDto dto = mapper.Map<OrderDto>(order); 

The above line will go into the controller. However, I do not understand where this config variable config ? How can I enter IMapper in the controller?

+6
source share
1 answer

First, create a MapperConfiguration and from it an IMapper , for which all your types are configured as follows:

 var config = new MapperConfiguration(cfg => { //Create all maps here cfg.CreateMap<Order, OrderDto>(); cfg.CreateMap<MyHappyEntity, MyHappyEntityDto>(); //... }); IMapper mapper = config.CreateMapper(); 

Then register the mapper instance with the unity container as follows:

 container.RegisterInstance(mapper); 

Then, any controller (or service) that wants to use the converter can declare such a dependency in the constructor as follows:

 public class MyHappyController { private readonly IMapper mapper; public MyHappyController(IMapper mapper) { this.mapper = mapper; } //Use the mapper field in your methods } 

Assuming you configured the MVC framework properly, the controller should be constructive without any problems.

+11
source

All Articles