AutoMapper dependency injection .Net 6

Bob Code
2 min readOct 20, 2023

--

In .NET 6, you can use the built-in dependency injection (DI) container along with AutoMapper to set up mapping profiles. Here’s a step-by-step guide on how to configure dependency injection and AutoMapper in a .NET 6 program:

  1. Create a new .NET 6 console application or web application (MVC, API, etc.) or use an existing one.
  2. Install the required NuGet packages if you haven’t already:
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection

3. Define your data models and DTOs. For example:

// Data model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

// Data Transfer Object (DTO)
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

4. Create AutoMapper profiles to define how your data models should be mapped to DTOs. Create a class that extends Profile and configure your mappings. For example:

public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Product, ProductDto>();
}
}

Alternatively your file might look like this

public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ProductDocument, ProductDocument_DTO>();
CreateMap<ProductModelDocument, ProductModelDocument_DTO>()
.ForMember(dest => dest.Variants, opt => opt.Ignore());
}
}

Or even simpler like that

public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<CollectionHeader_DTO, CollectionHeader>().ReverseMap();
CreateMap<ProductEntry_Header_DTO, ProductEntry_Header>().ReverseMap();
}
}


5. Configure AutoMapper and Dependency Injection in your program’s Program.cs file. Here's a sample Program.cs:

using AutoMapper;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;

// Add AutoMapper with a custom mapping profile
services.AddAutoMapper(typeof(MappingProfile));

// Configure other services
// ...

var app = builder.Build();

// Configure the app
// ...

app.Run();

6. With this setup, you can now use dependency injection to inject IMapper into your services or controllers:

public class ProductService
{
private readonly IMapper _mapper;

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

public ProductDto MapProductToDto(Product product)
{
return _mapper.Map<ProductDto>(product);
}
}

That’s it! You’ve set up AutoMapper and Dependency Injection in your .NET 6 program. You can now use ProductService (or any other service) to map your data models to DTOs.

--

--

Bob Code

All things related to Memes, .Net/C#, Azure, DevOps and Microservices