Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper in a class library

Tags:

automapper

I create a class library to put my repositories, domain model and my DTO. When a user call ClienteRepository.GetById(1) for exemple, it should get the Client domain model and transform into a ClientDTO to return this, 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 doesn't work because I did not create the map (Mapper.CreateMap<Client, ClientDTO>()).

My question: How can I do this in a class library if I dont have global.asax to create it?

like image 433
MuriloKunze Avatar asked Sep 26 '12 14:09

MuriloKunze


2 Answers

You don't need a Global.asax for Automapper. It's just the better way to do mapping init 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 simply do this in the constructor of your Repository.

like image 142
Cybermaxs Avatar answered Oct 27 '22 17:10

Cybermaxs


I solved my 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>();
        }
    }
}
like image 35
MuriloKunze Avatar answered Oct 27 '22 19:10

MuriloKunze