AutoMapper in the class library

I am creating a class library to host my repositories, domain model, and my DTO. For example, when a user calls ClienteRepository.GetById (1), he must get the client's domain model and convert to ClientDTO in order to return this, for example:

public class ClientRepository{ public ClientDTO GetById(int id){ var clientDto = Mapper.Map<Client, ClientDTO>(_db.Client.Find(id)); return clientDto; } } 

the problem is that Mapper.Map is not working because I did not create a map ( Mapper.CreateMap<Client, ClientDTO>() ).

My question is: how to do this in the class library if I don't have global.asax to create it?

+6
source share
2 answers

I solved the problem using https://github.com/davidebbo/WebActivator . Just create a new class and put this code:

 [assembly: WebActivator.PostApplicationStartMethod(typeof (MapsInit), "Activate")] namespace Database { public static class MapsInit { public static void Activate() { Mapper.CreateMap<ClienteDto, Cliente>(); Mapper.CreateMap<Cliente, ClienteDto>(); } } } 
+8
source

You do not need Global.asax for Automapper. This is the best way to do init mapping for a web project.

Just put your init code in a static constructor

  static MyStaticCtor() { //samples //Mapper.CreateMap<AccountViewModel, Account>(); //Mapper.CreateMap<AccountSettingViewModel, AccountSetting>() Mapper.AssertConfigurationIsValid(); } 

or even, you can just do it in the constructor of your repository.

+7
source

Source: https://habr.com/ru/post/926315/


All Articles