Configure Automapper in ASP.NET Core – Getting Started

Configure Automapper in ASP.NET Core – Getting Started

Today in this article we will see how to configure Automapper in C# ASP.NET Core or MVC application pipeline leveraging dependency injection.

AutoMapper is an object mapper that helps you transform one object of one type into an output object of a different type.

This type of transformation is often needed when you work on business logic.

Automapper helps to centralize your repeated boring mapping logic, address the separation of concerns, and provide better control on mapping making your code clean and easy to maintain.

AutoMapper simplifies the process of mapping data between objects in .NET applications, leading to cleaner, more maintainable code, reduced human error, and faster development. It’s a valuable tool for improving code quality and developer productivity when working with complex data structures and object-to-object mapping scenarios.

Today in this article, we will cover below aspects,

Here the idea with Automapper usage is simple, You have source type and destination type.

You just transform object values from one source to the destination object.

All you need is two types and profile registration. We will see what is profile registration in detail below.

Automapper in ASPNET Core map one object to another Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Why use AutoMapper?

  • Reduces Code duplication

AutoMapper significantly reduces the amount of repetitive code needed to map properties from one object to another.

Without AutoMapper, you would have to write custom code for each mapping, which can be time-consuming and error-prone. AutoMapper automates this process, making your codebase cleaner and more maintainable.

  • Centralize your mapping logic

Automapper Reduces Boilerplate Code. It significantly reduces the amount of repetitive code needed to map properties from one object to another.

  • Better controlled mapping

Manual mapping can lead to human errors, such as missing or mismatched property assignments. AutoMapper reduces the risk of such errors because it automatically matches properties with the same name and type. You can also configure custom mappings for non-standard cases.

  • Easy maintenance of code

As your application evolves and your data models change, you can update the AutoMapper configuration to reflect these changes. This helps ensure that your mappings stay up to date without requiring extensive modifications throughout your codebase.

  • Separation of conerns.

AutoMapper enhances the readability of your code by encapsulating mapping logic in a central configuration. This means that mapping details are defined in one place, making it easier for developers to understand and modify the mappings as needed.

  • Automapper dependency injection

Using AutoMapper makes it easier to write unit tests for your code. You can test your mapping logic in isolation, making it simpler to verify that the mappings are working correctly.

Getting started

Create ASP.NET Core 3.1 or .NET 6 API ro above application.

Automapper in ASPNET Core Getting started Csharp DI Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Please install below NuGet Automapper package from the Nuget Package Manager console,

PM> Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 8.0.1

OR

Install from NuGet Package Manager,

Nuget install AutoMapperExtensionsMicrosoftDependencyInjection Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Step 1 – Enable Automapper in API

Please enable Automapper using the below code in the ConfigureServices method in Startup.cs,

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAutoMapper(typeof(Startup).Assembly);
        }

Above AddAutomapper does below basic things,

  • Add singleton for the MapperConfiguration . MapperConfiguration adds the required profiles as registered in the code.

  • Add transient instance for IMapper

  • Adds value resolvers, member value resolvers, type converters to the IoC DI container.

Step 2- Configuring Profile Instances

Profiles are one of the best way of organizing all your mapping configurations in one place.

Here you need to create a class that inherits from the class Profile then please add your configuration of mapping into the Constructor.

Here is a sample implementation,

Automapper create Profile CSharp example Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Step 3- Automapper profile dependency injection- IMapper into the module

With the above two steps completed, you are all set to perform Dependency Injection of the IMapper interface wherever you need it.

You can inject IMapper using Constructor dependency injection into Controller or Domain layer or Data layer as needed.

Here is an example of dependency injection using Constructor injection,

Automapper DI Constructor injection IMapper in Controller Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Let’s write the Mapping logic of one object into an object of another type.

I have below two basic types called Source and Destination.

public class Source
    {
        public string  FirstName { get; set; }
        public string Address { get; set; }
        public string Id  { get; set; }

    }

  public class Destination
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Identity  { get; set; }

    }

The above types are unrelated and have different property names defined.

Lets now Map the Source object to the Destination object as below,

Sample examples,

        
        [HttpPost]
        public IActionResult UpdateEmployee([FromBody] Employee employee)
        {
            var destObject = _mapper.Map<Destination>(employee);

            _logger.LogInformation("Mapping successful");

            return Ok(destObject);
        }


Automapper in ASPNET Core mapping generics Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Finally, the source and destination JSON created can be found below,

Automapper in ASPNET Core Getting started 1 Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

Support for Basic Generic Types

Automapper supports all basic generic types with simple and easy mapping.

Your code just needs to use source and target references using generics like List or Arrays etc in the mapping code and you are done! It’s simple to map generics.

All below generic types are supported,

  • IEnumerable
  • IEnumerable<T>
  • ICollection
  • ICollection<T>
  • IList
  • IList<T>
  • List<T>
  • Arrays

The above same example can be converted to generic types,

List<Destination> destObject = _mapper.Map<List<Destination>>(sourcelist);

Automapper mapping generics list or array Configure Automapper in ASPNET Core Getting started | TheCodeBuzz

As per Automapper documentation Configuration should only happen once per AppDomain. That means we need to DI the configuration once i.e MapperConfiguration as a singleton instance.

References: Automapper – Ignore mapping property

That’s all! Happy Coding!

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

Today in this article we learned how to configure Automapper in the ASP.NET Core application. AutoMapper is an object mapper to transform one object of one type into an output object of a different type. Automapper helps you centralize your repeated boring mapping logic, and provides better control on mapping making your code clean and easy to maintain.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “Configure Automapper in ASP.NET Core – Getting Started”

  1. Adolfo Gutierrez

    la parte de DI IMapper en el módulo
    en ningún momento explican de que parte salió, me podría decir en que momento se crea o genera?

    1. Thanks Adolfo for your query. I see IMapper is introduced for DI in ASP.NET Core based API. I am not sure about the timelines. please visit the Automapper website for the documentation.
      Cheers!

Leave a Comment

Your email address will not be published. Required fields are marked *