How can I find the automapper profiles from the mapping?

5.2k views Asked by At

I have a lots of mapping profiles, how can I find the correct mapping configuration from specific map operation in source code? Can Resharper or a Visual Studio extension help?

I would like to jump from this:

var userDto = this.mapper.Map<User, UserDto>(user);

to this:

MapperConfiguration config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<User, UserDto>(MemberList.None);
    /*etc...*/
});

It is possible? How could I realize it?

1

There are 1 answers

0
plog17 On

What about isolating your mapping in its own class.

public class UserProfile: Profile
{
    public UserProfile()
    {
       CreateMap<User, UserDto>(MemberList.None);
    }
}

Your Profiles registration may differ, but here is how they could be dynamically registered.

public class MapperProvider
{
    private readonly Container container;

    public MapperProvider(Container container)
    {
        this.container = container;
    }

    public IMapper GetMapper()
    {
        var mce = new MapperConfigurationExpression();
        mce.ConstructServicesUsing(container.GetInstance);

        MapperConfiguration mc = GetMapperConfiguration(mce);
        IMapper m = new Mapper(mc, t => container.GetInstance(t));

        return m;
    }

    public static MapperConfiguration GetMapperConfiguration(MapperConfigurationExpression mce)
    {
        var profiles = typeof(ApplicationProfile).Assembly.GetTypes()
            .Where(t => typeof(Profile).IsAssignableFrom(t))
            .ToList();

        mce.AddProfiles(profiles);

        var mc = new MapperConfiguration(mce);
        mc.AssertConfigurationIsValid();
        return mc;
    }
}

That way, you can search for that profile class by its name, and easily navigate to your mapping.

It will work if you know that User mappings are in the UserProfile class.