14
votes

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?

1
You should configure the container to map between IMapper and the mapper instance. Then you should declare a dependency on IMapper from the controller (by accepting an IMapper in the constructor).Yacoub Massad
any example? So will there be `new MapperConfiguration()' for each entity i need to map? Example would be really helpLP13

1 Answers

28
votes

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.