How to implement AutoMapper 5.0.2

5

I set up a project a while back, as follows, A class named AutoMapperConfig as follows:

public class AutoMapperConfig
{
    public static void RegisterMappings()
    {
        Mapper.Initialize(x =>
        {
            x.AddProfile<DomainToViewModelMappingProfile>();
            x.AddProfile<ViewModelToDomainMappingProfile>();
        });
    }
}

Another class: DomainToViewModelMappingProfile that maps Domain to ViewModel:

public class DomainToViewModelMappingProfile : Profile
{
    public override string ProfileName
    {
        get { return "ViewModelToDomainMappings"; }
    }

    protected override void Configure()
    {
        Mapper.CreateMap<UsuarioViewModel, Usuario>();
    }
}

and one that maps from ViewModel to the Domain:

public class ViewModelToDomainMappingProfile : Profile
{
    public override string ProfileName
    {
        get { return "DomainToViewModelMappings"; }
    }

    protected override void Configure()
    {
        Mapper.CreateMap<Usuario, UsuarioViewModel>();
    }
}

And Controller Where I call a method where I get all users saved in the database

 public ActionResult Index()
 {
   var UsuarioViewModel= Mapper.Map<IEnumerable<Usuario>, IEnumerable<UsuarioViewModel>>(_usuarioApp.ObterTodos());
   return View(UsuarioViewModel);
 }

And lastly in Global.asax call AutoMapperConfig.RegisterMappings ();

This already worked perfectly the mapping for this context ... But I have seen that from version 4.2 of AutoMapper this type of configuration is obsolete. How do I implement the new form framework?

    
asked by anonymous 28.07.2016 / 05:10

1 answer

8

Renan, at this point little has changed, but now you need to store your Mapper in a static variable.

public class AutoMapperConfig
{
    public static IMapper Mapper { get; private set; }
    public static void RegisterMappings()
    {
        AutoMapperConfig.Mapper = new MapperConfiguration((mapper) =>
        {
            mapper.AddProfile<DomainToViewModelMappingProfile>();
            mapper.AddProfile<ViewModelToDomainMappingProfile>();
        });
    }
}

To call the mapper, you have to do this:

public ActionResult Index()
{
    var UsuarioViewModel = AutoMapperConfig.Mapper.Map<IEnumerable<Usuario>, IEnumerable<UsuarioViewModel>>(_usuarioApp.ObterTodos());
    return View(UsuarioViewModel);
}

The configuration call in Global.asax continues the same way. But now you have control of how to organize and more freedom in configuring, for example you can create multiple% s of% s.

One suggestion, you do not need to have a Profile for each mapping, this helps as much as putting all the mappings in the same file so try to group somehow, for example a IMapper of Profile .

Finally, I see that Domain and Usuario are identical, since I do not see any transformation or omission of data, it would be best if UsuarioViewModel works directly with UsuarioController without having to do the Mapping .

    
29.07.2016 / 15:09