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<T>
{
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<Type> 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<T> GetImplementations(IEnumerable<Type> types)
{
var implementations = types.Where(/* lambda to identify instantiable types which implement this interface */
.Select(x => CreateInstance(x));
return implementations;
}
public IEnumerable<T> 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();