AutoMapper - how to use custom value resolver inside custom type converter

Pawel Maga picture Pawel Maga · Oct 15, 2015 · Viewed 19k times · Source

How can I use custom value resolvers inside custom type converter? Currently, it seems to me hard to achieve. Do you know a way to how I can use this class?


Person converter

class PersonConverter : ITypeConverter<PersonData, Person>
{
    public Person Convert(ResolutionContext context)
    {
        var personData = context.SourceValue as PersonData;
        if (personData == null)
        {
            return null;
        }

        var person = new Person
        {
            Name = personData.Name
        };
        //person.Dic = // use here my DictionaryResolver

        return person;
    }
}

Model

class Person
{
    public string Name { get; set; }
    public Dictionary Dic { get; set; }
}

class PersonData
{
    public string Name { get; set; }
    public int DicId { get; set; }
}

class Dictionary
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Value resolver

class DictionaryResolver : ValueResolver<int, Dictionary>
{
    protected override Dictionary ResolveCore(int source)
    {
        // do something
        return new Dictionary
        {
            Id = source,
            Name = "Name"
        };
    }
}

Answer

stuartd picture stuartd · Oct 15, 2015

Custom value resolvers are designed for overriding the mapping of a specific member, when AutoMapper is going to map the objects:

Mapper.CreateMap<PersonData, Person>()
                .ForMember(dest => dest.Dic, opt => opt.ResolveUsing<DictionaryResolver>());

However, when you use a custom type resolver, this takes complete control of the mapping: there is no way of customising how one particular member is mapped:

Mapper.CreateMap<TPersonData, Person>().ConvertUsing(PersonConverter ); // No ForMember here.

However, given that you have complete control during type conversion, there is nothing stopping you from reusing the value converter, you just have to reference it specifically: however you will have to add a public method which returns the protected method ResolveCore:

class DictionaryResolver : ValueResolver<int, Dictionary>
{
    public Dictionary Resolve(int source)
    {
        return ResolveCore(source);
    }

    protected override Dictionary ResolveCore(int source)
    {
        // do something
        return new Dictionary
        {
            Id = source,
            Name = "Name"
        };
    }
}

Then during type conversion you call it to resolve that property:

var person = new Person
    {
        Name = personData.Name
    };

DictionaryResolver resolver = new DictionaryResolver();
person.Dic = resolver.Resolve(personData.IntValue); // whatever value you use