automapperautomapper-5

How to reuse ValueResolver across different mappings in AutoMapper 5?


I just tried upgrading AutoMapper to 5.0.2 but hit a road block.

According to the migration docs, value resolvers have now access to the destination object:

The signature of a value resolver has changed to allow access to the source/destination models.

This has the consequence that each value resolver is tied to exactly one destination type.

However, some of our value resolvers are used for multiple destination types. We have e.g. a resolver that is used during the mapping of all the ID properties of our DTOs. The resolver modifies the ID by means of a service that is injected into the resolver.

How would I define reusable value resolvers in AutoMapper 5, so that I don't have to create dedicated resolvers for each destination type with exactly the same implementation?

Note: The main reason to use a value resolver instead of directly manipulating the values is dependency injection. As per this answer, value resolvers are the best way to use a dependency-injected service during the mapping.


Solution

  • The destination type can just be "object":

    public class FooResolver : IValueResolver<object, object, string> {}
    

    Or it can be more specific:

    public class FooResolver : IValueResolver<IEntity, object, string> {}
    

    Because of the variance defined for IValueResolver, you can put base types in the first two generic arguments.