Search code examples
c#asp.net-coreautomapper

How to set up Automapper in ASP.NET Core


What are the basic steps to setting up automapper?


Solution

  • I figured it out! Here's the details:

    1. Add the main AutoMapper Package to your solution via NuGet.
    2. [Pre-v13.x] If using AutoMapper prior to v13.x, add the AutoMapper Dependency Injection Package to your solution via NuGet. However, do note::

    This package has been deprecated as it is legacy and is no longer maintained.

    1. Create a new class for a mapping profile. (I made a class in the main solution directory called MappingProfile.cs and add the following code.) I'll use a User and UserDto object as an example.

       public class MappingProfile : Profile {
           public MappingProfile() {
               // Add as many of these lines as you need to map your objects
               CreateMap<User, UserDto>();
               CreateMap<UserDto, User>();
           }
       }
      
    2. Then add the AutoMapperConfiguration in the Startup.cs as shown below:

       public void ConfigureServices(IServiceCollection services) {
           // .... Ignore code before this
      
          // Auto Mapper Configurations
           var mapperConfig = new MapperConfiguration(mc =>
           {
               mc.AddProfile(new MappingProfile());
           });
      
           IMapper mapper = mapperConfig.CreateMapper();
           services.AddSingleton(mapper);
      
           services.AddMvc();
      
       }
      
    3. To invoke the mapped object in code, do something like the following:

       public class UserController : Controller {
      
           // Create a field to store the mapper object
           private readonly IMapper _mapper;
      
           // Assign the object in the constructor for dependency injection
           public UserController(IMapper mapper) {
               _mapper = mapper;
           }
      
           public async Task<IActionResult> Edit(string id) {
      
               // Instantiate source object
               // (Get it from the database or whatever your code calls for)
               var user = await _context.Users
                   .SingleOrDefaultAsync(u => u.Id == id);
      
               // Instantiate the mapped data transfer object
               // using the mapper you stored in the private field.
               // The type of the source object is the first type argument
               // and the type of the destination is the second.
               // Pass the source object you just instantiated above
               // as the argument to the _mapper.Map<>() method.
               var model = _mapper.Map<UserDto>(user);
      
               // .... Do whatever you want after that!
           }
       }