C# reflection instantiation
- by NickLarsen
I am currently trying to create a generic instance factory for which takes an interface as the generic parameter (enforced in the constructor) and then lets you get instantiated objects which implement that interface from all types in all loaded assemblies.
The current implementation is as follows:
public class InstantiationFactory
{
protected Type Type { get; set; }
public InstantiationFactory()
{
this.Type = typeof(T);
if (!this.Type.IsInterface)
{
// is there a more descriptive exception to throw?
throw new ArgumentException(/* Crafty message */);
}
}
public IEnumerable GetLoadedTypes()
{
// this line of code found in other stack overflow questions
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a = a.GetTypes())
.Where(/* lambda to identify instantiable types which implement this interface */);
return types;
}
public IEnumerable GetImplementations(IEnumerable types)
{
var implementations = types.Where(/* lambda to identify instantiable types which implement this interface */
.Select(x = CreateInstance(x));
return implementations;
}
public IEnumerable GetLoadedImplementations()
{
var loadedTypes = GetLoadedTypes();
var implementations = GetImplementations(loadedTypes);
return implementations;
}
private T CreateInstance(Type type)
{
T instance = default(T);
var constructor = type.GetConstructor(Type.EmptyTypes);
if (/* valid to instantiate test */)
{
object constructed = constructor.Invoke(null);
instance = (T)constructed;
}
return instance;
}
}
It seems useful to me to have my CreateInstance(Type) function implemented as an extension method so I can reuse it later and simplify the code of my factory, but I can't figure out how to return a strongly typed value from that extension method.
I realize I could just return an object:
public static class TypeExtensions
{
public object CreateInstance(this Type type)
{
var constructor = type.GetConstructor(Type.EmptyTypes);
return /* valid to instantiate test */ ? constructor.Invoke(null) : null;
}
}
Is it possible to have an extension method create a signature per instance of the type it extends?
My perfect code would be this, which avoids having to cast the result of the call to CreateInstance():
Type type = typeof(MyParameterlessConstructorImplementingType);
MyParameterlessConstructorImplementingType usable = type.CreateInstance();