Automapper different profiles for each project in .Net Core Solution

Viewed 3045

I have a .Net Core 2.1 solution with the following structure

Infrastructure (automapper added here) << ApplicationCore (most of the logic services are here) << MVC

Infrastructure (automapper added here) << ApplicationCore (most of the logic services are here) <

(just to be clear the Infrastructure & ApplicationCore Class Library projects only exist once)

The ApplicationCore, MVC & Web API projects all have Classes/DTOs/View models specific to them. So having a single profile in the start up file of the MVC and/or API project could work, but would involve some duplication.

Also for testing I would like to run the ApplicationCore without the MVC or API projects.

Is there a good example project that shows how to have different profiles for each project?

1 Answers

I have same problem. Here is the solution in my way,

  1. I created 'MapperProfiles ' in Application core library inheriting the 'Profile'

    public class MapperProfiles : Profile
    {
        public MapperProfiles()
        {
            CreateMap<YourModel, YourViewModel>();
            CreateMap<YourViewModel, YourModel>();
        }
    }
    
  2. Added startup.cs to following line,

    services.AddAutoMapper(typeof(MapperProfiles));
    
  3. Now Controller modified as,

    private readonly IMapper _mapper;
    
    public YourController(ApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }
    
  4. now you can use mapper in controller ,

    YourModel model = _mapper.Map<YourModel >(YourViewModel);
    
Related