I've come across the same issue when working with AutoMapper, and @Behnam-Esmaili is a good answer but it could be improved.
You could implement a extension method for IMapperConfigurationExpression
which would do this two way mapping and also expecting two optional parameter (Action<IMappingExpression<T, Y>>
) which would be used when trying to configure the Mappings for both types.
public static class ModelMapper
{
private static readonly IMapper _mapper;
static ModelMapper()
{
var mapperConfiguration = new MapperConfiguration(config =>
{
config.CreateTwoWayMap<CustomerViewModel, Customer>(
secondExpression: (exp) => exp.ForMember((source) => source.CustomerEmail, opt => opt.MapFrom(src => src.Email)));
});
_mapper = mapperConfiguration.CreateMapper();
}
public static void CreateTwoWayMap<T, Y>(this IMapperConfigurationExpression config,
Action<IMappingExpression<T, Y>> firstExpression = null,
Action<IMappingExpression<Y, T>> secondExpression = null)
{
var mapT = config.CreateMap<T, Y>();
var mapY = config.CreateMap<Y, T>();
firstExpression?.Invoke(mapT);
secondExpression?.Invoke(mapY);
}
public static T Map<T>(object model)
{
return _mapper.Map<T>(model);
}
}
The implementation above is a one way of achieving it, however it can be design differently.