Codementor Events

How to using AutoMapper on ASP.NET Core 3.0 via Dependency Injection

Published Oct 13, 2019Last updated Oct 29, 2019

Step 1. Install AutoMapper extension from Package Manager in your project

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 7.0.0

Step 2. Register a service in CinfigureServices on Startup.cs

// Startup.cs
using AutoMapper;
public void ConfigureServices(IServiceCollection services){
    services.AddAutoMapper(typeof(Startup));
}

Step 3. Create a model and a data transfer object

// User.cs
// The model you want to map from
public class User{
    public string Name {get;set;}
    public string Email {get;set;}
    public string Phone {get;set;}
// Constructor to initialize User
    public User(){
        Name = "Nicky";
        Email = "myemail@gmail.com";
        Phone = "+81234588";
    }
}
// UserDTO.cs
// The data transfer object you want to map to
public class UserDTO{
    public string Name{get;set;}
    public string Email{get;set;}
    public string Phone{get;set;}
}

Step 4. Create an AutoMapping class file to register a mapping relation

// AutoMapping.cs
using AutoMapper;
public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<User, UserDTO>(); // means you want to map from User to UserDTO
    }
}

Step 5. Map User to UserDTO in code

// HomeController.cs
using AutoMapper;
public class HomeController : Controller
{
    private readonly IMapper _mapper;
    public HomeController(IMapper mapper)
    {
        _mapper = mapper;
    }
    public IActionResult GetUser()
    {
        User user = new User();
        var userDTO = _mapper.Map<UserDTO>(user);
        return View(userDTO);
    }
}

Finally, you got a dto object:

var name = userDTO.Name; // name = "Nicky"
var email = userDTO.Email; // email = "myemail@gmail.com"
var phone = userDTO.Phone; // phone = "+81234588"

Reference:

https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/7.0.0?_src=template

Discover and read more posts from Nicky Liu
get started
post comments4Replies
Fadi Hindash
5 years ago

Hi again,

this was missing
services.AddAutoMapper(c=>c.AddProfile<AutoMapping>(), typeof(Startup));

Fadi Hindash
5 years ago

Hi,

How to configure the AutoMapping Class
cause I have the same steps but I get this error
Missing type map configuration or unsupported mapping

so the Class AutoMapping is not used in the Startup class

thanks

Ian Carr
5 years ago

This is a great post - particularly for a ageing programmer like me!. I can even forgive the American English " I got …"

Derek Coleman
5 years ago

Then you also forgive Shakespeare too. Its possible Shakespeare spoke similar to some US accents than the RP on the BBC today.

Show more replies