Anton
Anton

Reputation: 2636

How to use mapper.Map inside MapperConfiguration of AutoMapper?

I need to map an object to another one using AutoMapper. The tricky question is how can I access an instance of the mapper (instance of IMapper) inside of the mapping configuration or inside of a custom type converter?

The code below does not work, however it is an example of what I would like to achieve - please notice the mapper.Map calls and assume that mappings Customer => CustomerDto and Customer => DetailedCustomerDto are defined.

var config = new MapperConfiguration(
    cfg => cfg.CreateMap<Order, OrderDto>()
        .ForMember(dst => dst.Customer, src => src.ResolveUsing(o => {
            return o.Type == 1
                ? mapper.Map<Customer, CustomerDto>(o.Customer)
                : mapper.Map<Customer, DetailedCustomerDto>(o.Customer)
            })
    );

The client part is:

var mapper = config.CreateMapper();
var orderDto = mapper.Map<Order, OrderDto>(order);

The simplified version of objects I want to map is:

public class Order
{
    public int Type { get; set; }
    public Customer Customer { get; set; }
}

public class Customer
{
    public long Id { get; set; }
    public string Name { get; set; }
}

public class OrderDto
{
    public CustomerDto Customer { get; set; }
}

public class CustomerDto
{
    public long Id { get; set; }
}

public class DetailedCustomerDto : CustomerDto
{
    public string Name { get; set; }
}

As you see from the code above, based on the value of Order.Type, the mapper should map the property Order.Customer to different targets. As one target (DetailedCustomerDto) inherits from the other one (CustomerDto) it becomes a bit tricky.

Please notice that usage of the obsolete and deprecated static method Mapper.Map is NOT an option.

Upvotes: 49

Views: 46932

Answers (3)

Evk
Evk

Reputation: 101453

As of AutoMapper 8.0 and up

The answer below for 5.1.1 still applies, except that ResolveUsing has been renamed to MapFrom; the delegate signature remains the same.

As of AutoMapper 5.1.1

You can get to the mapper using the overload of ResolveUsing that accepts a delegate with four parameters, the last of which is ResolutionContext that has a Mapper property (context.Mapper in the below snippet):

var config = new MapperConfiguration(
    cfg => {
        cfg.CreateMap<Customer, CustomerDto>();
        cfg.CreateMap<Customer, DetailedCustomerDto>();
        cfg.CreateMap<Order, OrderDto>()
             .ForMember(dst => dst.Customer, src => src.ResolveUsing(
                  (order, orderDto, i, context) => {
                      return order.Type == 1
                      ? context.Mapper.Map<Customer, CustomerDto>(order.Customer)
                      : context.Mapper.Map<Customer, DetailedCustomerDto>(order.Customer);
        }));
 });

 var orderTypeOne = new Order();
 orderTypeOne.Type = 1;
 orderTypeOne.Customer = new Customer() {
    Id = 1
 };

 var dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeOne);
 Debug.Assert(dto.Customer.GetType() == typeof (CustomerDto));

 var orderTypeTwo = new Order();
 orderTypeTwo.Type = 2;
 orderTypeTwo.Customer = new Customer() {
     Id = 1
 };
 dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeTwo);
 Debug.Assert(dto.Customer.GetType() == typeof (DetailedCustomerDto));

Prior to AutoMapper 5.1.1

You can get to the mapper using an overload of ResolveUsing with two parameters, first of which is ResolutionResult (result.Context.Engine.Mapper):

var config = new MapperConfiguration(
    cfg => {
        cfg.CreateMap<Customer, CustomerDto>();
        cfg.CreateMap<Customer, DetailedCustomerDto>();
        cfg.CreateMap<Order, OrderDto>()
             .ForMember(dst => dst.Customer, src => src.ResolveUsing((result, order) => {
                return order.Type == 1
                ? result.Context.Engine.Mapper.Map<Customer, CustomerDto>(order.Customer)
                : result.Context.Engine.Mapper.Map<Customer, DetailedCustomerDto>(order.Customer);
        }));
 });

 var orderTypeOne = new Order();
 orderTypeOne.Type = 1;
 orderTypeOne.Customer = new Customer() {
    Id = 1
 };

 var dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeOne);
 Debug.Assert(dto.Customer.GetType() == typeof (CustomerDto));

 var orderTypeTwo = new Order();
 orderTypeTwo.Type = 2;
 orderTypeTwo.Customer = new Customer() {
     Id = 1
 };
 dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeTwo);
 Debug.Assert(dto.Customer.GetType() == typeof (DetailedCustomerDto));

Upvotes: 89

Rodolfo Luna
Rodolfo Luna

Reputation: 957

I'm using Automapper 9 and the answers above didn't work for me. Then for resolve my problem that is like yours I use .afterMap, like that:

public class AutoMapperOrder : Profile
{
        public AutoMapperOrder()
        {
            CreateMap<Customer, CustomerDto>()
            //...

            CreateMap<Customer, DetailedCustomerDto>()
            //...

            CreateMap<Order, OrderDto>()
                .AfterMap((src, dest, context) => {
                dest.Customer = src.Type == 1
                    ? context.Mapper.Map<Customer, CustomerDto>(src.Customer)
                    : context.Mapper.Map<Customer, DetailedCustomerDto>(src.Customer)
            }
        }
    }
}

I hope to help somebody.

Upvotes: 19

Breeno
Breeno

Reputation: 3156

In addition to Evk's great answer, which helped me, if you need to do a mapping inside a mapping inside a config/profile that requires a custom constructor (i.e. the type has no default constructor), the following will work in v5.2.0:

CreateMap<Models.Job, Models.API.Job>(MemberList.Source);

CreateMap<StaticPagedList<Models.Job>, StaticPagedList<Models.API.Job>>()
                .ConstructUsing((source, context) => new StaticPagedList<Models.API.Job>(
                    context.Mapper.Map<List<Models.Job>, List<Models.API.Job>>(source.ToList()),
                    source.PageNumber,
                    source.PageSize,
                    source.TotalItemCount));

In this example I'm mapping the X.PagedList custom collection type of one object type onto an equivalent collection of another object type. The first parameter to the lamdba expression is your source object, the second is your ResolutionContext from which you can access a mapper instance to map from.

Upvotes: 16

Related Questions