5

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?

cSteusloff
  • 2,487
  • 7
  • 30
  • 51
  • Could using a `all references` of User or UserDto be enough ? For sure, one of those references would be in that `CreateMap` method. – plog17 Feb 12 '18 at 16:12
  • Other than that, personnally, I tend to isolate mapping in there own file, and name them with the same suffix every time. That way, I can search for UserProfile and be 100% sure I'll end up in the right class file. – plog17 Feb 12 '18 at 16:14
  • @plog17, in a large projects with 99+ references, this is not an alternative. I have a class for every domain object with to many methods. I can find the mapping in less than 20 seconds, but without any automatic way :( – cSteusloff Feb 12 '18 at 16:20
  • 1
    Oh I see, I posted an alternative that would rely on having a naming convention of your profiles. It proved to be enough on project I have been working on. To be honest, I am also interested in what people can propose to ease that kind of operation. – plog17 Feb 12 '18 at 16:23

1 Answers1

0

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.

plog17
  • 832
  • 8
  • 23