简体   繁体   中英

Automapper Dynamic Resolver's

I'm trying to create an abstract layer on top of automapper which enables users to dynamically add custom rules to each property they map.

Given the Model

public class Entity
{
    public int Index { get; set; }
}

public class DTO
{
    public int Count { get; set; }
}

we may configure Automapper to map the entities like so:

//sorry this is pseudo coded
cfg.CreateMap<Entity, DTO>()
    .ForMember(dest => dest.Index, 
        opt => opt.ResolveUsing<IndexResolver>());


public class IndexResolver: ValueResolver<DTO, int>, 
{
    protected override string ResolveCore(DTO source)
    {
        return source.Count - 1;
    }
}

This works since we map the rule to a Value resolver, However if I wanted to create a rule at run time is that possible. I would like to be able to configure things like so:

cfg.CreateMap<Entity, DTO>()
    .ForMember(dest => dest.Index, 
        opt => opt.Resolver(d => d.Count - 1);

Is there a way I can Add a resolver with an expression so I do not need to inherit from ValueResolver?

My first thought is to create a generic custom resolver that takes an expression in its constructor. You should then be able to do:

.ResolveUsing(new LambdaResolver(d => d.Count - 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM