How to configure Auto mapper in class library project?

bnil picture bnil · Oct 20, 2014 · Viewed 20.2k times · Source

I am using auto mapping first time.

I am working on c# application and I want to use auto mapper.

(I just want to know how to use it, so I don't have asp.net app neither MVC app.)

I have three class library projects.

enter image description here

I want to write transfer process in the service project.

So I want to know how and where should I configure the Auto Mapper ?

Answer

Marko picture Marko · Mar 23, 2018

So based on Bruno's answer here and John Skeet's post about singletons I came up with the following solution to have this run only once and be completely isolated in class library unlike the accepted answer which relies on the consumer of the library to configure the mappings in the parent project:

public static class Mapping
{
    private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() =>
    {
        var config = new MapperConfiguration(cfg => {
            // This line ensures that internal properties are also mapped over.
            cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
            cfg.AddProfile<MappingProfile>();
        });
        var mapper = config.CreateMapper();
        return mapper;
    });

    public static IMapper Mapper => Lazy.Value;
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Source, Destination>();
        // Additional mappings here...
    }
}

Then in your code where you need to map one object to another you can just do:

var destination = Mapping.Mapper.Map<Destination>(yourSourceInstance);

NOTE: This code is based on AutoMapper 6.2 and it might require some tweaking for older versions of AutoMapper.