Skip to content

Instantly share code, notes, and snippets.

@KevM
Created October 29, 2012 13:58
Show Gist options
  • Save KevM/3973710 to your computer and use it in GitHub Desktop.
Save KevM/3973710 to your computer and use it in GitHub Desktop.
StructureMap generic AddAllTypes workaround until pull request 48 gets accepted
//TODO Kill this with fire once StructureMap gets fixed
public class GenericFindAllTypesFilter : IRegistrationConvention
{
private readonly Type _pluginType;
private Func<Type, string> _getName = type => PluginCache.GetPlugin(type).ConcreteKey;
public GenericFindAllTypesFilter(Type pluginType)
{
_pluginType = pluginType;
}
public void Process(Type type, Registry registry)
{
if (type.CanBeCastTo(_pluginType) && Constructor.HasConstructors(type))
{
string name = _getName(type);
registry.AddType(GetLeastSpecificButValidType(_pluginType, type), type, name);
}
}
private Type GetLeastSpecificButValidType(Type pluginType, Type type)
{
if (pluginType.IsGenericTypeDefinition && !type.IsOpenGeneric())
return type.FindFirstInterfaceThatCloses(pluginType);
return pluginType;
}
public void NameBy(Func<Type, string> getName)
{
_getName = getName;
}
}
public class MyRegistry : Registry
{
public MyRegistry()
{
Scan(s =>
{
s.With(new GenericFindAllTypesFilter(typeof (MyOpenGenericType<>));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment