Last active
December 31, 2015 22:28
-
-
Save martijnburgers/8053310 to your computer and use it in GitHub Desktop.
Our AutoMapperProfileConvention. Finds AutoMapper Profiles and checks if they have accessible contstructors. We have been searching for hours why a certain profile was not registered in the AutoMapper configuration until we saw that for some reason it had a private constructor :-)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Finds all automapper profile type and checks if the profile type has accessible constructors, if not it will throw an exception. | |
/// Accesible constructors are needed for IoC. | |
/// </summary> | |
public class AutoMapperProfileConvention : IRegistrationConvention | |
{ | |
private Func<Type, string> _getName = type => PluginCache.GetPlugin(type).ConcreteKey; | |
private readonly Type _pluginType; | |
public AutoMapperProfileConvention() | |
{ | |
_pluginType = typeof(Profile); | |
} | |
public void Process(Type type, Registry registry) | |
{ | |
if (type == _pluginType) | |
return; | |
if (!type.CanBeCastTo(_pluginType)) | |
return; | |
if (!Constructor.HasConstructors(type)) | |
{ | |
throw new InvalidProgramException(String.Format("The profile of type: {0} has no accessible constructor!", type)); | |
} | |
string name = _getName(type); | |
registry.AddType(GetLeastSpecificButValidType(_pluginType, type), type, name); | |
} | |
private Type GetLeastSpecificButValidType(Type pluginType, Type type) | |
{ | |
if (pluginType.IsGenericTypeDefinition) | |
return type.FindFirstInterfaceThatCloses(pluginType); | |
return pluginType; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where is PluginCache defined?