AutoMapper is a convention based object-object mapper. It maps two different entities by transforming an input object of one type to an output object of another type.

In this post, we will setup Automapper in ASP.Net core project, assuming you have some prior knowledge of Automapper.

 

Installing Automapper

In package manager console, install the following Nuget package:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

In ConfigureService method of Startup.cs, add AutoMapper as service:

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

 

Adding Profiles

AutoMapper has this concept called profiles, in a profile, you can store all related mappings. You create a profile by creating a class and deriving it from Profile class in AutoMapper and create mappings inside the constructor.

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<User, UserDto>();
    }
}

At runtime, Automapper will scan the code for classes that inherit from Profile and it creates the mapping defined in the constructor.

 

Using IMapper

You can inject IAutoMapper as constructor injection in any controller and use it in action:

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

public IActionResult Index()
{
    var user = _mapper.Map<UserDto>(user);
    // logic here
}

 

Simple enough right? Please leave suggestions or comments in the comments section below.