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; }
}
Join the conversation! Your thoughts help the community grow.