AutoMapper is well known in the .NET community. It bills itself as “a simple little library built to solve a deceptively complex problem - getting rid of code that maps one object to another,” and it does the job nicely.
In the past, I’ve used it exclusively with ASP.NET APIs. However, the method for utilizing it via dependency injection has changed. So let’s review how to get started, how to define mappings and how to inject our mappings into ASP.NET Core APIs.
Like most .NET libraries, we can install the
AutoMapper package from Nuget.
For our purposes, we’ll focus on two classes that are related;
These classes will serve as source and destination types that we can work with.
Without specific configuration, AutoMapper will match properties based on their name. By default, it will ignore null reference exceptions when mapping source and destination types. Below is a snippet mapping the source and destination types using the default configuration.
The above will create a
UserDTO object with an
Name that matches the original
user object, but no error is thrown as a result of not having the
UserDTO type. Also, the
BirthYear property of the
UserDTO will be zero.
We can use projection to translate properties as they are mapped. For instance, the code snippet
below shows how we can map the
BirthDate property of the
User type to the
property of the
userDTO object will be similar to our first example, but this time it will
BirthYear property of 2000.
A clean way to organize and maintain our mapping configurations is with profiles. Many
Profile classes will encapsulate business areas (e.g. Ordering, Shipping). To
start, we’ll create a class that inherits from
Profile and put the configuration in the
For added isolation, we can create a project just for our
Profile configurations. Using
profiles helps us keep configurations more manageable as our application grows.
Dependency injection is baked into ASP.NET Core, but to use AutoMapper with it we’ll need additional configuration and an additional Nuget package.
Once installed, we can define the configuration using profiles. In the
method, we can use the
AddAutoMapper extension method on the
IServiceCollection object as
With AutoMapper registered and its configurations set, we can now inject an
IMapper we can map our objects to their DTO equivalents using the
Wrap It Up
Now that ASP.NET Core is injecting AutoMapper to our controllers, we can add configurations to our profiles or create new profiles for new business areas and still map appropriately without further configuration.
Of course, we didn’t cover all of the features of AutoMapper so I’d suggest checking out their documentation for more information about their capabilities. Hopefully this post gave you enough information to start trying AutoMapper yourself. Let me know in the comments how you use AutoMapper in your applications.