Skip to content

Instantly share code, notes, and snippets.

@martijnburgers
Last active December 31, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martijnburgers/8053310 to your computer and use it in GitHub Desktop.
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 :-)
/// <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;
}
}
@futurechan
Copy link

Where is PluginCache defined?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment