3

I have a set of classes I would like to map to with Automapper. However, every class has a constructor parameter. This parameter is of the same type for all members, but I do not know the value to supply until the point I want to do my mapping.

I have found the ConstructUsing method, but that requires me to specify the parameter value at time of configuration. I would prefer to do it at time of Mapping to avoid needing to create a separate MappingEngine for every instance of the parameter. I have found the Map overload that maps to an already created destination object. This is helpful, but it does not work for lists or object graphs.

Essentially, I am looking for something like this resolve method from Autofac, only applied to Automapper's Map method.

Resolve<IFoo>( new TypedParameter( typeof( IService ), m_service) );

1 Answer 1

8

Reading through the Automapper source code, I found a workable solution which I described below.

First, you need to specify you want to use a Service Locator for construction.

IConfiguration configuration = ...;
configuration.CreateMap<Data.Entity.Address, Address>().ConstructUsingServiceLocator();

Then when calling map, you specify a specific service locator using the opts parameter

// Use DI container or manually construct function
// that provides construction using the parameter value specified in question.
// 
// This implementation is somewhat Primitive, 
// but will work if parameter specified is always the only parameter
Func<Type, object> constructingFunction =
    type => return Activator.CreateInstance( type, new object[] { s_service } );

mappingEngine.Map<Data.Entity.Address, Address>(
    source, opts: options => options.ConstructServicesUsing( constructingFunction );

The "ServiceLocator" indicated by constructingFunction above takes precedent over the function provided to IConfiguration.ConstructServicesUsing(...)

Sign up to request clarification or add additional context in comments.

2 Comments

If Adam were still with us, I'm sure he would give you lots of details about any other way of accomplishing this. Unfortunately, he died in July. I'm his Dad and have just gotten access to this account and thought I would reach out since you commented today.
Very sorry for your loss. Seemed like a smart guy. May he rest in peace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.