Reputation: 2083
I want to create an universal wrapper for AutoMapper mapping engine. My final goal is to be tied to an interface.
public interface IMappingEngine
{
TDestination Map<TSource, TDestination>(TSource source);
}
I will resolve it with DI.
Then I create an implementation of this interface based on AutoMapper MappingEngine
.
public class AutoMapperMappingEngine : IMappingEngine
{
private readonly ConfigurationStore configurationStore;
private readonly MappingEngine mappingEngine;
public AutoMapperMappingEngine()
{
this.configurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
this.RegisterMappings();
this.configurationStore.AssertConfigurationIsValid();
this.mappingEngine = new MappingEngine(this.configurationStore);
}
/// <summary>
/// This method registers alternate mappings for already existing mappings.
/// </summary>
private void RegisterMappings()
{
// some code
// this.configurationStore.CreateMap<>
}
public TDestination Map<TSource, TDestination>(TSource source)
{
TDestination mappingResult = this.mappingEngine.Map<TDestination>(source);
return mappingResult;
}
}
But I stuck with a problem. What happen if I will need more than two different mappings for the same pair of types?
IMappingEngine autoMapperMappingEngine;
// Initialize autoMapperMappingEngine
FooModel result;
if(firstCondition)
{
result = autoMapperMappingEngine.Map<FooEntity, FooModel>(entity);
}
else
{
if(secondCondition)
{
result = autoMapperMappingEngine.Map<FooEntity, FooModel>(entity);
}
else
{
result = autoMapperMappingEngine.Map<FooEntity, FooModel>(entity);
}
}
If I register a few different mappings in sequence inside of RegisterMappings
the last mapping will overlap the rest. Could you give some advises how to implement what I want?
Upvotes: 0
Views: 1506
Reputation: 6427
Use the Instance API instead;
https://github.com/AutoMapper/AutoMapper/wiki/Static-and-Instance-API
This involves creating a configuration and using that to map, so that you can have multiple configurations... You will of course have to extend your interface
Upvotes: 1