ASP MVC with Automapper Profiles
IMapper interface is injected into constructors of my classes by Unity framework, but you can use any other DI framework or inject IMapper interface manually.
I really like automapper functionality and I find it really useful especially when binding objects between layers. And I had a real struggle to make this work. So this should be hopefully a simple tutorial for those who would like to move from static Mapper class to IMapper interface. Or for those who never used AutoMapper before and would like to learn how to wire it all up. Because most of the tutorials I found were incomplete or out of date (using static Mapper class).
If you have only one layer where you need to map between your models I would recommend not to use AutoMapper Profiles and just go with simple solution.
This way you create your MapperConfiguration object with all your mappings.
You can then create IMapper object from this configuration and inject it into your DI framework (Unity in my case)
On line 7 MapperConfiguration is created and from that configuration by calling .CreateMapper() we get IMapper object.
On line 8 IMapper interface is binded to this mapper object (from line 7).
So from now on every time when DI sees IMapper object in constructor it will provide this mapper object(line 7 again).
Now example of object that requires IMapper:
This could be usage of automapper. You can use IMapper interface public method Map<> to map your classes. IMapper object is injected either by DI framework or manually when you create the BaseService object.
More than one layer
In real world MVC application you usually have more than one layer. You probably have something like WEB/BUSINESS/DB layer and WEB should not know about DB, because it talks only to BUSINESS layer.
That means that with one configuration class you would have to reference DB project in you Web layer, otherwise you couldn’t map you objects.
And here come for help automapper Profiles.
MappingProfile class again, now with profiles
This way Web layer doesn’t need to reference DB layer.
All other steps are same as for one layer.
I think that automapper can be very useful tool if used properly, but it is sometime really hard to find tutorials that are up to date. I highly recommend to read autommaper wiki if you struggle.