fbpx

Configure AutoMapper library in ASP.NET Core project

Reading time: 2 minutes

Are you looking to configure AutoMapper in ASP.NET Core project? Sometime its very strenuous to map two dissimilar object types in ASP.NET. 

AutoMapper is a component which helps to reuse and copy data from one object type to other with just few lines of code. For more details about AutoMapper library go to this link.

As there is a difference in ASP.NET MVC and Core project structure, and if you want to configure AutoMapper library in ASP.NET Core application then follow these simple steps.

Solution

1. Open Package Manager Console. From top menu bar go to:

View -> Other Windows -> Package Manager Console

   * Install AutoMapper package:

Install-Package AutoMapper -Version 6.2.2

 * Install AutoMapper Dependency Injection package:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 3.2.0

2. In startup.cs file, define AddAutoMapper function inside ConfigureServices function and don’t forget to use ‘Alt, Enter‘ keyboard shortcut to import library. 

public void ConfigureServices(IServiceCollection services) {
    // Before anycode...
    services.AddMvc(); 
    // Include here  
    services.AddAutoMapper(typeof(Startup));
    // After anycode...
}
AddAutoMapper function in configure service class for AutoMapper
AddAutoMapper in ConfigureService

3. Create a new class for a mapping profile, I made it in solution’s main directory. You can make it where you wish e-g: MappingProfile.cs

public class MappingProfile : Profile {
    public MappingProfile() {       
        CreateMap<Object, ObjectDto>();
        CreateMap<ObjectDto, Object>();
    }
}
AutoMapper library mapping profile code example
MappingProfile

4. At last just Invoke mapping object in Controller:

public class UserController : Controller {
    private readonly IMapper _mapper;

    // Assign in constructor for dependency injection
    public UserController(IMapper mapper) {
        _mapper = mapper;
    }

    public async Task Edit(string id) {
        var user = await _context.Users
            .SingleOrDefaultAsync(u => u.Id == id);
        var model = _mapper.Map<User, UserDto>(user);
        // some code ....
    }
}

Share your love with us 😉

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply