From the blog: 30 days of BuiltWithDot.Net. Thank you, status update and roadmap.

How-to: setup AutoMapper in asp.net core

 

Mapping objects is never fun. AutoMapper makes the process less painful. What's the correct way of using AutoMapper with asp.net core? Read on.

by Corstiaan Hesselink

Last updated: Wednesday May 16, 2018Reading time: 6 minutes

You already know that software development has it’s share of tedious, routine and downright boring tasks. One task that can make you doubt your career choices is… mapping objects. Mapping objects manually is the developers version of an intern charged with coffee & copies.

Mapping objects also magnifies the tug of war between the part of you that wants to create a neat and maintainable app, and the part that wants to be productive in the short term. In a moment of desperation you have even considered dynamic or Expando objects… Let’s not dig any deeper.

You would have not become a developer if there wouldn’t a easier way to go about mapping objects. Enter AutoMapper.

The difference? Dependency injection

Although this post is about AutoMapper, what makes it specific to asp.net core is the fact that dependency injections (or DI) is a first class citizen in asp.net core. This makes using AutoMapper in the right way a bit different compared to earlier versions of .net, unless you were manually using DI in a previous version of .net. You can read up on DI here and here. Also make sure you know what a container is (or ServiceCollection in asp.net core lingo)

So, how do we setup AutoMapper in asp.net core using DI?

Let’s consider the following Startup.cs. We’ll focus on the ConfigureServices method for now as that is the place where we will configure our AutoMapper dependency (or service).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace AutoMapperDemo
{
    public class Startup
    {
        [...]

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        [...]
    }
}

The second step is to create and configure an MapperConfiguration instance like so:

1
2
3
4
5
6
7
8
9
10
11
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var config = new AutoMapper.MapperConfiguration(cfg =>
    {
        cfg.CreateMap<UserViewModel, Models.User>();
    });

    IMapper mapper = config.CreateMapper();
}

If you are familiar with AutoMapper this setup is nothing new. The difference is that you will not be using it immediately after you instantiate it, as we’ll see in a bit. Also notice how we are using a common situation: mapping between a domain model (Models.User) and a view model (UserViewModel).

So, how do we use this instance of IMapper at some other place in our app? This requires one final line to register the IMapper instance as a service with the asp.net core DI container, like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var config = new AutoMapper.MapperConfiguration(cfg =>
    {
        cfg.CreateMap<UserViewModel, Models.User>();
    });

    IMapper mapper = config.CreateMapper();

    services.AddSingleton(mapper);
}

Notice how we are using the services.AddSingleton method. This makes sure that, instead of a new instance, the same instance of IMapper gets used every time an IMapper instance gets requested by a constructor in your code. Consider the following controller.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace AutoMapperDemo.Controllers
{
    public class HomeController : Controller
    {
        IMapper _mapper;

		public HomeController(IMapper mapper)
		{
			_mapper = mapper;
		}

        public IActionResult Index()
        {
			var user = new User
			{
				Name = "Pete",
				Email = "pete@petessite.com"
			};
            
			var viewModel = _mapper.Map<UserViewModel>(user);
			                  
            return View(viewModel);
        }
    }
}

Notice how the controller’s constructor requires an instance of IMapper and set’s that instance as the value of the private field _mapper. The asp.net core DI system automatically injects the IMapper instance you configured in Startup.cs into HomeController when HomeController gets instantiated. This makes the mapper available in your controller code, as you can see in the Index function of the controller. There you can use the mapper as usual.

And there you go: a quick setup of AutoMapper using asp.net core dependency injection.

Never miss an update!

Be the first to discover new articles just like this one. Delivered directly to your inbox, with my no-spam-guarantee™. Unsubscribe any time.