Automapper in ASP.NET Core

By | September 6, 2017

AutoMapper is an object-object mapper which allows you to solve the problem of manually mapping each property of a class with the same properties of another class. Read in details.

How to use Automapper in ASP.NET Core

1) Add the main AutoMapper Package to your solution via NuGet.

PM> Install-Package AutoMapper 

or

 

2)  Add the AutoMapper Dependency Injection Package to your solution via NuGet.

PM> Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

or

 

3)  Call the AddAutoMapper() extension from Startup.cs as shown below.

public void ConfigureServices(IServiceCollection services)
{

    services.AddAutoMapper(); // <-- This is the line you add.
    // services.AddAutoMapper(typeof(Startup));  // <-- newer automapper version uses this signature.
}

4)  Create a new class for a mapping profile. (I made a class in the service solution directory called MappingProfile.cs  and add the following code.). I’ll use a User and UserDto object as below example.

using MyProject.DAL;
using MyProject.Models;
using AutoMapper;

namespace MyProject.Service
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            //Map the objects
            CreateMap<UserDto, User>();
            CreateMap<AttributesDto, Attributes>().ReverseMap();
        }
    }
}

.ReverseMap() is a method which is used for mapping vise versa.

5)  To invoke the mapped object in code, do something like the following:

public class UserController : Controller
{

    // Create a field to store the mapper object
    private readonly IMapper _mapper;

    // Assign the object in the constructor for dependency injection
    public UserController(IMapper mapper)
    {
        _mapper = mapper;
    }

    public async Task Get(string id)
    {

        // Instantiate source object
        // (Get it from the database or whatever your code calls for)
        var user = await _context.Users
            .SingleOrDefaultAsync(u => u.Id == id);

        // Instantiate the mapped data transfer object
        // using the mapper you stored in the private field.
        // The type of the source object is the first type argument
        // and the type of the destination is the second.
        // Pass the source object you just instantiated above
        // as the argument to the _mapper.Map<>() method.
        var model = _mapper.Map<User, UserDto>(user);

        // .... Do whatever you want after that!
    }
}

 

I hope you will enjoy the Automapper in ASP.NET Core. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Like it? Share it
  • LearnReasonExplore

    A search for “Unable to resolve service for type AutoMapper.IMapper” got me here and you solved my problem. GeeksBlood had the only match on Google for that. Thank you!