Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Automapper with unity dependancy injection?

I am planning to use Automapper with ASP.NET MVC solution and Unity DI. The video posted on automapper on how to use is very old and doesn't show how mapper can be used with dependency injection. Most of the examples on stackoverflow also uses Mapper.CreateMap() method which is now deprecated.

The automapper guide says

Once you have your types you can create a map for the two types using a MapperConfiguration instance and CreateMap. You only need one MapperConfiguration instance typically per AppDomain and should be instantiated during startup.

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

So i am assuming above line of code will go into application startup, like global.asax

To perform a mapping, create an IMapper use the CreateMapper method.

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

The above line will go into controller. However i am not understanding where this config variable coming from? How do i inject IMapper in controller?

like image 467
LP13 Avatar asked May 04 '16 21:05

LP13


People also ask

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

What can I use instead of AutoMapper?

AutoMapper is one of the popular object-object mapping libraries with over 296 million NuGet package downloads. It was first published in 2011 and its usage is growing ever since. Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.


1 Answers

First, create a MapperConfiguration and from it an IMapper that has all your types configured like this:

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 like this:

container.RegisterInstance(mapper);

Then, any controller (or service) that wishes to use the mapper can declare such dependency at the constructor like this:

public class MyHappyController
{
    private readonly IMapper mapper;

    public MyHappyController(IMapper mapper)
    {
        this.mapper = mapper;
    }

    //Use the mapper field in your methods
}

Assuming that you set up the container correctly with the MVC framework, the controller should be constructable without an issue.

like image 195
Yacoub Massad Avatar answered Oct 18 '22 01:10

Yacoub Massad