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!

Back to blog
  • ChatGPT Uncovered Podcast

    ChatGPT Uncovered Podcast

    Pedro Martins

    ChatGPT Uncovered Podcast ChatGPT Uncovered Podcast Exploring the Frontiers of AI Conversational Models Episode 1: Understanding ChatGPT Published on: May 15, 2023 Your browser does not support the audio element....

    ChatGPT Uncovered Podcast

    Pedro Martins

    ChatGPT Uncovered Podcast ChatGPT Uncovered Podcast Exploring the Frontiers of AI Conversational Models Episode 1: Understanding ChatGPT Published on: May 15, 2023 Your browser does not support the audio element....

  • Power Apps In-Depth Podcast

    Power Apps In-Depth Podcast

    Pedro Martins

    Power Apps In-Depth Podcast Power Apps In-Depth Podcast Exploring the Capabilities of Microsoft Power Apps Episode 1: Introduction to Power Apps Published on: April 20, 2023 Your browser does not...

    Power Apps In-Depth Podcast

    Pedro Martins

    Power Apps In-Depth Podcast Power Apps In-Depth Podcast Exploring the Capabilities of Microsoft Power Apps Episode 1: Introduction to Power Apps Published on: April 20, 2023 Your browser does not...

  • Exploring Power Pages Podcast

    Exploring Power Pages Podcast

    Pedro Martins

    Exploring Power Pages Podcast Exploring Power Pages Podcast Delving into the World of Microsoft Power Pages Episode 1: Getting Started with Power Pages Published on: March 10, 2023 Your browser...

    Exploring Power Pages Podcast

    Pedro Martins

    Exploring Power Pages Podcast Exploring Power Pages Podcast Delving into the World of Microsoft Power Pages Episode 1: Getting Started with Power Pages Published on: March 10, 2023 Your browser...

1 of 3