Use of Automapper in ASP.NET Core

AutoMapper is a popular library in .NET for simplifying object-to-object mapping, such as converting between Data Transfer Objects (DTOs) and domain models in ASP.NET Core applications.

Step-by-step guide on how to use AutoMapper in an ASP.NET Core application.

1. Install AutoMapper Packages

First, you'll need to install the necessary AutoMapper packages. You can do this via NuGet Package Manager.

The primary packages are.

  • AutoMapper
  • AutoMapper.Extensions.Microsoft.DependencyInjection (for integrating with ASP.NET Core)

2. Create Mapping Profiles

Define your mapping configurations in profile classes. A profile is a class that inherits from the Profile and specifies the mappings.

using AutoMapper;
// Define a profile for your mappings
public class MappingProfile : Profile
{
    public MappingProfile()
    {
        // Create mappings between DTOs and domain models
        CreateMap<SourceModel, DestinationModel>();
        CreateMap<AnotherSourceModel, AnotherDestinationModel>();
    }
}

3. Configure AutoMapper in ASP.NET Core

In your Startup class (for ASP.NET Core 3.1 and earlier) or Program class (for .NET 5 and later), configure AutoMapper.

For .NET 5 and later

In Program.cs

using AutoMapper;
var builder = WebApplication.CreateBuilder(args);
// Add AutoMapper services
builder.Services.AddAutoMapper(typeof(Program)); // or specify the profile class directly
var app = builder.Build();

For ASP.NET Core 3.1 and earlier

In Startup. cs

using AutoMapper;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add AutoMapper services
        services.AddAutoMapper(typeof(MappingProfile)); // or specify the profile class directly

        // Other service configurations
    }
    // Other methods
}

4. Inject and Use AutoMapper

You can now inject IMapper into your services or controllers and use it to perform mappings.

For example, in a controller.

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
public class MyController : ControllerBase
{
    private readonly IMapper _mapper;
    public MyController(IMapper mapper)
    {
        _mapper = mapper;
    }
    public IActionResult Get()
    {
        var source = new SourceModel(); // Assume this is obtained from a database or other source
        var destination = _mapper.Map<DestinationModel>(source);
        return Ok(destination);
    }
}

5. Define Your Models

Make sure you have your source and destination models defined.

public class SourceModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class DestinationModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Example

Let's create a simple weather forecast example using AutoMapper in an ASP.NET Core application.

1. Models

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public string Summary { get; set; }
}

DTOs

public class WeatherForecastDto
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public string Summary { get; set; }
}

2. Create a Mapping Profile

Define a mapping profile to map between WeatherForecast and WeatherForecastDto.

using AutoMapper;
public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<WeatherForecast, WeatherForecastDto>();
    }
}

3. Configure AutoMapper in ASP.NET Core

For .NET 5 and later

using AutoMapper;
var builder = WebApplication.CreateBuilder(args);
// Add AutoMapper services
builder.Services.AddAutoMapper(typeof(MappingProfile));
var app = builder.Build();

For ASP.NET Core 3.1 and earlier

using AutoMapper;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add AutoMapper services
        services.AddAutoMapper(typeof(MappingProfile));

        // Other service configurations
    }
    // Other methods
}

4. Create a Weather Forecast Service

Create a service to provide weather forecast data.

public class WeatherForecastService
{
    public WeatherForecast GetWeatherForecast()
    {
        // In a real application, this data might come from a database or API
        return new WeatherForecast
        {
            Date = DateTime.Now,
            TemperatureC = 25,
            Summary = "Sunny"
        };
    }
}

5. Create a Controller

Create a controller that uses AutoMapper to return weather forecast data as DTOs.

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly IMapper _mapper;
    private readonly WeatherForecastService _weatherForecastService;
    public WeatherForecastController(IMapper mapper, WeatherForecastService weatherForecastService)
    {
        _mapper = mapper;
        _weatherForecastService = weatherForecastService;
    }
    [HttpGet]
    public ActionResult<WeatherForecastDto> Get()
    {
        var forecast = _weatherForecastService.GetWeatherForecast();
        var forecastDto = _mapper.Map<WeatherForecastDto>(forecast);
        return Ok(forecastDto);
    }
}

6. Register the WeatherForecastService

Finally, register the WeatherForecastService in the dependency injection container.

var builder = WebApplication.CreateBuilder(args);
// Add AutoMapper and services
builder.Services.AddAutoMapper(typeof(MappingProfile));
builder.Services.AddScoped<WeatherForecastService>();
var app = builder.Build();

For ASP.NET Core 3.1 and earlier.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add AutoMapper and services
        services.AddAutoMapper(typeof(MappingProfile));
        services.AddScoped<WeatherForecastService>();

        // Other service configurations
    }
    // Other methods
}

Summary

  1. Define Models and DTOs: Create classes for your data models and their corresponding DTOs.
  2. Create a Mapping Profile: Set up mappings between models and DTOs.
  3. Configure AutoMapper: Register AutoMapper in your ASP.NET Core application.
  4. Implement a Service: Provide the data from a service.
  5. Create a Controller: Use AutoMapper in the controller to return the mapped DTOs.
  6. Register Services: Ensure all dependencies are registered in the DI container.


Similar Articles