Automapper - Instantiate Destination Using IoC

Introduction 

 
In this article, we examine how to configure Automapper to use IoC for instantiating new objects including Collections. 
 
Process 
  • Use IoC to instantiate Destination Type when mapped using Automapper
  • The SourceType-DestinationType mapping is done only at runtime as when the requirement arises. It is NOT done beforehand using Profile Classes.
  • Ignore all properties from Source that have been decorated with IgnoreDataMemberAttribute
  • Create a wrapper around Automapper which would enable you to accomplish the above-mentioned requirements.
For the sake of example, we will be using the following Nuget Packages:
  • Automapper 7.0.1
  • Caliburn Micro 3.2.0
  • Unity 5.11.4
  • NUnit 3.12.0

Writing Test Cases

 
Let's follow Test Driven Development for our purpose, and begin by writing our test cases.
  1. public void MapperDataTypeWithCollections()    
  2. {    
  3.     var valueMapper = new ValueMapper();    
  4.     var destinationFromIoC = Shared.TestModels.DataTypeWithCollections.Destination.GetInstanceForIoC();    
  5.     var userDefinedTypeFromIoC = Shared.TestModels.DataTypeWithCollections.UserDefinedType.GetInstanceForIoC();    
  6.     
  7.     var source = Shared.TestModels.DataTypeWithCollections.Source.GetInstance();    
  8.     var destination = valueMapper.Map<Shared.TestModels.DataTypeWithCollections.Source, Shared.TestModels.DataTypeWithCollections.Destination>(source);    
  9.     
  10.     Assert.AreNotSame(source, destination);    
  11.     Assert.AreEqual(source.Property1, destination.Property1);    
  12.     
  13.     Assert.AreNotEqual(source.Property2, destination.Property2);    
  14.     Assert.AreEqual(destinationFromIoC.Property2, destination.Property2);    
  15.     
  16.     Assert.AreNotSame(source.Property3, destination.Property3);    
  17.     Assert.AreEqual(source.Property3.Property1, destination.Property3.Property1);    
  18.     Assert.AreNotEqual(source.Property3.Property2, destination.Property3.Property2);    
  19.     Assert.AreEqual(userDefinedTypeFromIoC.Property2, destination.Property3.Property2);    
  20.     
  21.     CollectionAssert.AreNotEqual(source.Property4, destination.Property4);    
  22.     Assert.AreNotSame(source.Property4, destination.Property4);    
  23.     for (int i = 0; i < source.Property4.Count; i++)    
  24.     {    
  25.         Assert.AreNotSame(source.Property4[i], destination.Property4[i]);    
  26.         Assert.AreEqual(source.Property4[i].Property1, destination.Property4[i].Property1);    
  27.         Assert.AreNotEqual(source.Property4[i].Property2, destination.Property4[i].Property2);    
  28.         Assert.AreEqual(userDefinedTypeFromIoC.Property2, destination.Property4[i].Property2);    
  29.     }    
  30. }     
Data Structures used in the above test case are as follows:
  1. // Source  
  2. public class Source  
  3. {  
  4.     public string Property1 { getset; }  
  5.     [IgnoreDataMember]  
  6.     public string Property2 { getset; }  
  7.     public UserDefinedType Property3 { getset; }  
  8.     public List<UserDefinedType> Property4 { getset; }  
  9.   
  10.     public static Source GetInstance()  
  11.     {  
  12.         return new Source  
  13.         {  
  14.             Property1 = $"{nameof(Source)}.{nameof(Source.Property1)}",  
  15.             Property2 = $"{nameof(Source)}.{nameof(Source.Property2)}",  
  16.             Property3 = new UserDefinedType   
  17.             {   
  18.                 Property1 = $"{nameof(Source)}.{nameof(UserDefinedType)}.{nameof(UserDefinedType.Property1)}",   
  19.                 Property2 = $"{nameof(Source)}.{nameof(UserDefinedType)}.{nameof(UserDefinedType.Property2)}"   
  20.             },  
  21.             Property4 = Enumerable.Range(1, 5).Select(x =>  
  22.             new UserDefinedType  
  23.             {  
  24.                 Property1 = $"{nameof(Source)}.{nameof(UserDefinedType)}.{nameof(UserDefinedType.Property1)}[{x}]",  
  25.                 Property2 = $"{nameof(Source)}.{nameof(UserDefinedType)}.{nameof(UserDefinedType.Property2)}[{x}]"  
  26.             }).ToList()  
  27.         };  
  28.     }  
  29. }  
  30. // Destination  
  31. public class Destination  
  32. {  
  33.     public string Property1 { getset; }  
  34.     public string Property2 { getset; }  
  35.     public UserDefinedType Property3 { getset; }  
  36.     public List<UserDefinedType> Property4 { getset; }  
  37.   
  38.     public static Destination GetInstanceForIoC()  
  39.     {  
  40.         return new Destination  
  41.         {  
  42.             Property1 = $"IoC => {nameof(Destination)}.{nameof(Destination.Property1)}",  
  43.             Property2 = $"IoC => {nameof(Destination)}.{nameof(Destination.Property2)}",  
  44.             Property3 = UserDefinedType.GetInstanceForIoC(),  
  45.             Property4 = Enumerable.Range(1, 5).Select(x =>  
  46.             UserDefinedType.GetInstanceForIoC(x)).ToList()  
  47.         };  
  48.     }  
  49. }   
  50. // User Defined Type  
  51. public class UserDefinedType  
  52. {  
  53.     public string Property1 { getset; }  
  54.     [IgnoreDataMember]  
  55.     public string Property2 { getset; }  
  56.   
  57.     public static UserDefinedType GetInstanceForIoC()  
  58.     {  
  59.         return new UserDefinedType  
  60.         {  
  61.             Property1 = $"IoC => {nameof(UserDefinedType)}:{nameof(UserDefinedType.Property1)}",  
  62.             Property2 = $"IoC => {nameof(UserDefinedType)}:{nameof(UserDefinedType.Property2)}"  
  63.         };  
  64.     }  
  65.   
  66.     public static UserDefinedType GetInstanceForIoC(int index)  
  67.     {  
  68.         return new UserDefinedType  
  69.         {  
  70.             Property1 = $"IoC => {nameof(UserDefinedType)}:{nameof(UserDefinedType.Property1)}[{index}]",  
  71.             Property2 = $"IoC => {nameof(UserDefinedType)}:{nameof(UserDefinedType.Property2)}[{index}]"  
  72.         };  
  73.     }  
  74. }  

Definition of ValueMapper

 
First, let's define how our ValueMapper will look using the IValueMapperinterface.
 
ValueMapper interface
  1. public interface IValueMapper  
  2. {  
  3.     TDestination Map<TSource, TDestination>(TSource source);  
  4.     TDestination Map<TSource, TDestination>(TSource source,TDestination destination);  
  5. }  
Use IoC for instantiating Types
 
In order to create the mapping configurations in runtime, we make use of the MapperConfiguration and MapperConfigurationExpression classes.
  1. private readonly MapperConfigurationExpression _mapperConfigurationExpression = new MapperConfigurationExpression();  
  2. private IMapper _mapper;  
  3. private MapperConfiguration _mapperConfiguration;  
Begin by configuring the MappingConfigurationExpression to use IoC.
  1. _mapperConfigurationExpression.ConstructServicesUsing(CreateInstance);  
Where CreateInstance is defined as:
  1. private object CreateInstance(Type type)  
  2. {  
  3.     try  
  4.     {  
  5.         return Caliburn.Micro.IoC.GetInstance(type, null);  
  6.     }  
  7.     catch  
  8.     {  
  9.         return Activator.CreateInstance(type);  
  10.     }  
  11. }  
The CreateInstance method is quite self explainatory. If type is not registered with IoC, it attempts to create the type using the default contructor via Activator.CreateInstance method.
 
Ignore properties with IgnoreDataMemberAttribute
 
Before we put it all together, we need to configure the Automapper so that it will skip properties decorated with the IgnoreDataMemberAttribute.
 
For this, we will write an extension on the IMappingExpression type.
  1. public static class IMappingExpressionExtensions  
  2. {  
  3.     public static IMappingExpression IgnoreAllPropertiesWithIgnoreDataMemberAttribute(  
  4.         this IMappingExpression expression, Type sourceType)  
  5.     {  
  6.         foreach (var property in sourceType.GetProperties().Where(x => x.GetCustomAttributes<IgnoreDataMemberAttribute>().Any()))  
  7.         {  
  8.             expression.ForMember(property.Name, opt => opt.Ignore());  
  9.         }  
  10.   
  11.         return expression;  
  12.     }  
  13. }  
As shown, we are iterating through each property of the Type, and marking the ones with the required Attribute.
 
The obvious question at this point would be, if one of the nested child properties of the Source has been decorated with the attribute, it would not be covered by the extension method we just wrote. We will address this problem shortly. For the time being, let's use MappingExpressionConfiguration to use the extension method we just created.
  1. _mapperConfigurationExpression.CreateMap(sourceType, destinationType)  
  2.                                 .IgnoreAllPropertiesWithIgnoreDataMemberAttribute(sourceType)  
  3.                                 .ConstructUsingServiceLocator();  
Putting it all together
 
The next step is to configure the Automapper to use the MappingConfigurationExpression we just created (updated).
  1. _mapperConfiguration = new MapperConfiguration(_mapperConfigurationExpression);  
  2. _mapper = new Mapper(_mapperConfiguration);  
We now need to ensure that the nested properties are taken care of. We will do so by recursively loop through the properties of Source Type.
  1. private void CreateMap(Type sourceType,Type destinationType)  
  2. {  
  3.     _mapperConfigurationExpression.ConstructServicesUsing(CreateInstance);  
  4.   
  5.     _mapperConfigurationExpression.CreateMap(sourceType, destinationType)  
  6.                                     .IgnoreAllPropertiesWithIgnoreDataMemberAttribute(sourceType)  
  7.                                     .IgnoreAllPropertiesWithNoDataMemberWhenTypeHasDataContractAttribute(sourceType)  
  8.                                     .ConstructUsingServiceLocator();  
  9.     _mapperConfiguration = new MapperConfiguration(_mapperConfigurationExpression);  
  10.     _mapper = new Mapper(_mapperConfiguration);  
  11.   
  12.     var sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  13.     foreach(var property in sourceProperties)  
  14.     {  
  15.         if (property.PropertyType.IsStringOrValueType())  
  16.         {  
  17.             continue;  
  18.         }  
  19.   
  20.         if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))  
  21.         {  
  22.             var elementType = property.PropertyType.GetGenericArguments()[0];  
  23.             CreateMap(elementType, elementType);  
  24.             continue;  
  25.         }  
  26.   
  27.         CreateMap(property.PropertyType, property.PropertyType);  
  28.     }  
  29. }  
As observed from the code, we are addressing only Public Instance properties for the sake of example. This could be extended to other properties if required.
 
Complete ValueMapper Code
 
The complete source code of ValueMapper is shown below.
  1. public class ValueMapper : IValueMapper  
  2. {  
  3.     private readonly MapperConfigurationExpression _mapperConfigurationExpression = new MapperConfigurationExpression();  
  4.     private IMapper _mapper;  
  5.     private MapperConfiguration _mapperConfiguration;  
  6.   
  7.     public ValueMapper()  
  8.     {  
  9.         _mapperConfiguration = new MapperConfiguration(_mapperConfigurationExpression);  
  10.         _mapper = _mapperConfiguration.CreateMapper();  
  11.     }  
  12.     public TDestination Map<TSource, TDestination>(TSource source)  
  13.     {  
  14.         var sourceType = typeof(TSource);  
  15.         var destinationType = typeof(TDestination);  
  16.   
  17.         CreateMap(sourceType, destinationType);  
  18.         return _mapper.Map<TSource, TDestination>(source);  
  19.   
  20.     }  
  21.     public TDestination Map<TSource, TDestination>(TSource source, TDestination destination)  
  22.     {  
  23.         var sourceType = typeof(TSource);  
  24.         var destinationType = typeof(TDestination);  
  25.         CreateMap(sourceType, destinationType);  
  26.         return _mapper.Map<TSource, TDestination>(source);  
  27.     }  
  28.     private void CreateMap(Type sourceType,Type destinationType)  
  29.     {  
  30.         _mapperConfigurationExpression.ConstructServicesUsing(CreateInstance);  
  31.   
  32.         _mapperConfigurationExpression.CreateMap(sourceType, destinationType)  
  33.                                         .IgnoreAllPropertiesWithIgnoreDataMemberAttribute(sourceType)  
  34.                                         .IgnoreAllPropertiesWithNoDataMemberWhenTypeHasDataContractAttribute(sourceType)  
  35.                                         .ConstructUsingServiceLocator();  
  36.         _mapperConfiguration = new MapperConfiguration(_mapperConfigurationExpression);  
  37.         _mapper = new Mapper(_mapperConfiguration);  
  38.   
  39.         var sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  40.         foreach(var property in sourceProperties)  
  41.         {  
  42.             if (property.PropertyType.IsStringOrValueType())  
  43.             {  
  44.                 continue;  
  45.             }  
  46.   
  47.             if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))  
  48.             {  
  49.                 var elementType = property.PropertyType.GetGenericArguments()[0];  
  50.                 CreateMap(elementType, elementType);  
  51.                 continue;  
  52.             }  
  53.   
  54.             CreateMap(property.PropertyType, property.PropertyType);  
  55.         }  
  56.     }  
  57.   
  58.     private object CreateInstance(Type type)  
  59.     {  
  60.         try  
  61.         {  
  62.             return Caliburn.Micro.IoC.GetInstance(type, null);  
  63.         }  
  64.         catch  
  65.         {  
  66.             return Activator.CreateInstance(type);  
  67.         }  
  68.     }  
  69. }  

Conclusion

 
The above article uses Automapper 7.0.1 for demonstrating the requirements. The approach could differ when using an older version of Automapper.
 
The sample source code along with this article is a WPF Project with Test Cases using NUnit.