ASP.NET Core: Getting Started with AutoMapper in ASP.NET Core via Dependency Injection

By FoxLearn 4/1/2020 9:30:34 PM   4.66K
This post shows you How to use AutoMapper.Extensions.Microsoft.DependencyInjection in ASP.NET Core.

AutoMapper is an object-object mapper that helps you map between two objects. Object-object mapping works by transforming an input object of one type into an output object of a different type.

AutoMapper.Extensions.Microsoft.DependencyInjection

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. It's a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types.

AutoMapper C# Net Core

After you finish creating an ASP.NET Core project, you need to right-click on your project, then select Manage Nuget Packages from your Visual Studio.

c# asp.net core automapper dependency injection

You need to search and install "AutoMapper.Extensions.Microsoft.DependencyInjection"

Opening your Startup class, then add a configuration as shown below.

//asp.net core 3 automapper
services.AddAutoMapper(typeof(Startup));

Creating a User class as shown below.

public class User
{
    public Guid Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
}

Next, Create a UserViewModel class to map data between Model and View as shown below.

public class UserViewModel
{
    public Guid Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
    public List<Role> Roles { get; set; }
}

public class Role
{

}

Creating an AutoMapping inheritance from the Profile class to register a mapping relation.

using AutoMapper;
//automapper .net core example
public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<User, UserViewModel>();
    }
}

Creating a UserController, then map User to UserViewModel class as shown below.

using AutoMapper;
//c# asp.net core automapper
public class UserController : Controller
{
    private readonly IMapper _mapper;
    private readonly IDataRepository _dataRepository;
    public UserController(IMapper mapper, DataRepository dataRepository)
    {
        _mapper = mapper;
        _dataRepository = dataRepository;
    }

    public IActionResult GetUser()
    {
        User user = _dataRepository.GetUser(1);
        var model = _mapper.Map<UserViewModel>(user);
        return View(model);
    }
}

As you can see, AutoMapper is a simple little library built to solve the complex problem of removing code mapping an object to another.

Related