views:

196

answers:

2

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();
+2  A: 

I don' think it is possible, because you are trying to get compile time type information (strongly typing) of types you only know at runtime. You will have to work with your interfaces.

The problem is, you don't know which types will be contained in your assemblies at compile tim. You could even use a variable for the name of your assembly! Your assembly may contain any implementation of your interface. So there is no possibilty to tell the compiler to create a strongly typed instance of the type you load from your assembly.

Simon
A: 

Maybe something like this? I don't see a way without a cast or a generic type param to handle the cast internally. I use something similar to this where I have a subclass Type object coming in, but use only base class methods etc. in the caller.

public static object New( this Type type )
{
    return type.GetConstructor( Type.EmptyTypes ).Invoke( null );
}

public static T New<T>( this Type type )
{
    return (T)type.GetConstructor( Type.EmptyTypes ).Invoke( null );
}

// usage
MyParameterless usable = (MyParameterless)type.New();
MyParameterless usable 2 = type.New<MyParameterless>();
BioBuckyBall
The problem with your approach is that you KNOW the type (you even wrote it down: 'MyParemeterless'). He doesn't as he loads it from an assembly.
Simon
Correct. In my own code where I use something simlilar, I don't know the actual runtime type, but I do know the base type. These are also loaded from assemblies (that I didn't write).See the example usage he gave 'Type type = typeof(MyParameterlessConstructorImplementingType);MyParameterlessConstructorImplementingType usable = type.CreateInstance();' and the qualifying sentence in my post 'I don't see a way without...'
BioBuckyBall