0
votes

I have a web solution which includes a web UI, web api layer, service objects, and a data layer which encapsulates repositories (sometimes using a Unit of Work pattern) and Entity Framework entities. My web service is returning JSON which I'm deserializing within the UI controller like this:

var response = await httpClient.GetAsync(endpoint);

var result = JsonConvert.DeserializeObject<anyTypeHere>(await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync());

My web api layer calls various "services" (all represented as their own library project - ie: Accounting Service, EnrollmentService, CalendarService). Within each service object is code to access data entities thru Repositories:

// returns entity object
var customer = UnitOfWork.PatientRepository.GetCustomerById();

I'd like to use a tool like AutoMapper to map entity objects to dto/domain objects thus returning the dto objects back to the UI caller.

My question are:

  1. Where should I add Automapper reference and mapping code? (ie: WebApi, service project, repository layer, etc...)

  2. Should I create a separate library that contains the DTO objects and reference this in my UI client as well as api and service layer(s)?

1

1 Answers

0
votes

create class Library project for your DTOs like YourProject.Dtos and transfer all your dtos to this project. then in another project(YourProject.Mapping) create interface:

 public interface IMapperProfile
{
}

use this interface for mapping signature like:

  public class AddressMapping : Profile, IMapperProfile
{
    public AddressMapping()
    {
        CreateMap<AddressDto, Address>(MemberList.None).ReverseMap();
    }
}

AddressRepositories methods must be like this:

 public async Task<IEnumerable<AddressDto>> GetAllAsync( CancellationToken cancellationToken = default)
    {
        var result = await _entity.AsNoTracking().ToListSync();
        return _mapper.Map<IEnumerable<AddressDto>>(result);
    }

now you can register Automapper in your api or ui startup class :

services.AddAutoMapper(typeof(IMapperProfile));