When you use external libraries you are forced to use their classes inside your own code. To make yourself more confident, it is wise to make your own classes simpler than external ones. Usually, in order to do this you have to do some manual code behind. AutoMapper helps you in that process by automatic mapping fields between classes and rewriting their fields. How does it work?
To start your mapping using AutoMapper you have to do two things
Firstly, you have to define the way how mapping should be carried out. The simplest example is:
This code snippet will create the new instance of Destination class with fields rewritten from a Source class. It is important to note that the fields are mapped by their names. If the name is different, current configuration will not handle these fields and will assign a null value.
More complex usage of AutoMapper
You can imagine how many different scenarios you may experience while converting one object instance to another. The whole list of AutoMapper features is available here. Below I will show the neatest snippets. I have found AutoMapper extremely useful in changing the collection objects from one to another. Imagine, you have LLBLGEN self servicing class that reprents the collection of products – ProductsCollection class. This class implements IEnumerable and contains products – ProductEntity class. You want to map it to IList<IProduct> object. This way you hide from the external code your LLBLGEN entity classes and you limit the amount of properties in IProduct interface.
To convert ProductEntity to IProduct you don’t need any additional classes. By the correct AutoMapper configuration you can perform your conversion pretty smoothly.
Now, you can convert your ProductEntity object to IProduct. In our example, we have ProductCollection class which we want to convert to IList<IProduct> object instance. AutoMapper is able to perform this conversion directly without defining additional mapping for our collection classes. Our conversion code is:
[csharp]varresult=Mapper.Map&lt;ProductCollection,IList&lt;IProduct&gt;&gt;(source);//source is an instance of ProductCollection class[/csharp]
How AutoMapper converts classes to interfaces?
In the above example, you are probably curiouse what kind of class is used to create the instance of object that is behind IProduct interface. This class is called DynamicProxy and is created by use of LinFu library. This way, we don’t have to create our own classes to map ProductEntity to IProduct interface. AutoMapper creates a custom proxy class for you.
AutoMapper is a useful library that speeds up your coding
Thanks to AutoMapper I avoided creating special proxy classes to map my domain object to more simple ones. This for sure can speed up your coding a little and makes your components less vulnerable to external libraries’ changes. Share your opinion and experience with us below or meet us on Twitter: @GOYELLO.