Vaughan

Using automapper in ASP.NET Core

.NET Core, Automapper

To be honest I have mixed feelings on using something like automapper by default but there are definitely cases when it heavily reduces the amount of code you write and therefore your bugs.

It has pretty good integration with ASP.NET Core so when it should be used, it won\'t take long to get started.

To do this you need to add the package:


AutoMapper.Extensions.Microsoft.DependencyInjection

Then in your ConfigureServices method you add the service and specificy which assembly to look for Profiles.


services.AddAutoMapper(Assembly.GetExecutingAssembly());

Then add the automapper Profile that will define the mappings in one place.


public class PersonViewModel 
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class ApplicationProfile : Profile 
{
    public ApplicationProfile()
    {
        CreateMap<PersonViewModel, Person>()
                    .ReverseMap();
    }
}

Then in your service you can just inject the IMapper interface and convert. Easy.


public class PersonService
{
    private readonly IMapper mapper;

    public PersonService(IMapper mapper)
    {
        this.mapper = mapper;
    }

    public void Save(PersonViewModel personViewModel)
    { 
        var person = mapper.Map<Person>(personViewModel);

        //Save person
    }
}

Related Posts

BMC logoBuy me a coffee