Setting Up AutoMapper in ASP.NET Core: A Step-by-Step Guide

Setting Up AutoMapper in ASP.NET Core: A Step-by-Step Guide

Integrating AutoMapper into your ASP.NET Core project can significantly simplify your object-to-object mappings, making your code cleaner and more maintainable. AutoMapper is a powerful library designed to automatically map properties between different objects, reducing the amount of manual mapping code you need to write. In this guide, we’ll walk you through the steps to set up AutoMapper in an ASP.NET Core application, from installation to configuration and usage.

Installing AutoMapper Dependencies

The journey begins by adding AutoMapper and its ASP.NET Core extensions to your project. This can be achieved effortlessly through the NuGet Package Manager or the Package Manager Console with the following command:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

This command not only installs AutoMapper but also its necessary extensions for a seamless integration with ASP.NET Core's dependency injection system.

Creating Mapping Profiles

Mapping profiles are at the heart of AutoMapper's functionality. These are classes where you define the source and destination types for your mappings. Create a profile by inheriting from the Profile class and defining your mappings in the constructor.

Create the two class User And UserDto

After configure the UserProfile Class

Here's how:

using AutoMapper;

public class UserProfile : Profile
{
    public UserProfile()
    {
        CreateMap<User, UserDto>();
        // Feel free to add more mappings here
    }
}


Configuring AutoMapper in Startup.cs

Once your mapping profiles are ready, it's time to configure AutoMapper in your application. This is done in the Startup.cs file, within the ConfigureServices method. Here's the code snippet to do just that:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(typeof(Startup)); // This works if your profiles are in the same assembly as Startup.cs
    // Alternatively, specify assemblies explicitly
    // services.AddAutoMapper(typeof(UserProfile).Assembly);
    
    // Don't forget to add frameworks services and any other services you might need
    services.AddControllersWithViews();
}
or in Program.cs
builder.Services.AddAutoMapper(typeof(Program));
// This works if your profiles are in the same assembly as Startup.cs
// Alternatively, specify assemblies explicitly
// services.AddAutoMapper(typeof(UserProfile).Assembly);

Utilizing AutoMapper

With AutoMapper configured, you can now inject the IMapper interface into controllers or services to perform object mappings. Below is an example of how to use AutoMapper in a controller:


using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplicationAutomapper.Models;

namespace WebApplicationAutomapper.Controllers
{
public class UsersController : ControllerBase
{
private readonly IMapper _mapper;

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

public IActionResult GetUserInfo(int userId)
{
User user = GetUserFromDatabase(userId); // Assuming this retrieves the User entity
UserDto userDto = _mapper.Map<UserDto>(user);
return Ok(userDto);
}

private User GetUserFromDatabase(int userId)
{
throw new NotImplementedException();
}
}
}

Testing Your Setup

The final step is to ensure your AutoMapper configuration works as expected. Test your endpoints or services that utilize AutoMapper to verify correct mappings. It’s crucial to ensure all properties are accurately mapped, and no data is missing or incorrectly transformed.

You can found all the code in this repo in GitHub:

 https://github.com/icpmtech/NLayer-Architecture/tree/master/WebApplicationAutomapper

By following these steps, you'll efficiently integrate AutoMapper into your ASP.NET Core project. AutoMapper not only reduces the amount of boilerplate code but also minimizes mapping errors, allowing you to focus on your application's core functionality. Happy coding!

Voltar para o blogue
  • ChatGPT Uncovered Podcast

    Podcast descoberto do ChatGPT

    Pedro Martins

    Podcast descoberto do ChatGPT Podcast descoberto do ChatGPT Explorando as fronteiras dos modelos de conversação de IA Episódio 1: Compreendendo o ChatGPT Publicado em: 15 de maio de 2023 Seu...

    Podcast descoberto do ChatGPT

    Pedro Martins

    Podcast descoberto do ChatGPT Podcast descoberto do ChatGPT Explorando as fronteiras dos modelos de conversação de IA Episódio 1: Compreendendo o ChatGPT Publicado em: 15 de maio de 2023 Seu...

  • Power Apps In-Depth Podcast

    Podcast detalhado do Power Apps

    Pedro Martins

    Podcast detalhado do Power Apps Podcast detalhado do Power Apps Explorando os recursos do Microsoft Power Apps Episódio 1: Introdução ao Power Apps Publicado em: 20 de abril de 2023...

    Podcast detalhado do Power Apps

    Pedro Martins

    Podcast detalhado do Power Apps Podcast detalhado do Power Apps Explorando os recursos do Microsoft Power Apps Episódio 1: Introdução ao Power Apps Publicado em: 20 de abril de 2023...

  • Exploring Power Pages Podcast

    Explorando o podcast Power Pages

    Pedro Martins

    Explorando o podcast Power Pages Explorando o podcast Power Pages Mergulhando no mundo das Power Pages da Microsoft Episódio 1: Primeiros passos com Power Pages Publicado em: 10 de março...

    Explorando o podcast Power Pages

    Pedro Martins

    Explorando o podcast Power Pages Explorando o podcast Power Pages Mergulhando no mundo das Power Pages da Microsoft Episódio 1: Primeiros passos com Power Pages Publicado em: 10 de março...

1 de 3