Question

I am loading a DLL up at runtime. The DLL and the main application both use a DLL witch holds interfaces that let the program know how to use some of the Types in the DLL. In the main application there is a Factory class where the Dll can set one of its object types to be created when the main application requests the interface it inherits from. below is the striped down (mainly removed error handling code) version of the function to create the object type from the DLL. When this gets called I get a Exception saying no parameterless constructor defined for this object. I dont know why because they all have parameterless constructors.

    //inside the DLL
    Factory.ResovleType<ISomething>(typeof(SomethingCool));

    //inside the main application
    ISomething obj = Factory.CreateObject<ISomething>();


    //inside the Factory Class
    public static T CreateObject<T>(params object[] args) 
    {
        T obj = (T)Activator.CreateInstance(resovledList[typeof(T)], args);

        return obj;
    }

    public static void ResolveType<T>(Type type)
    {
          resovledList.Add(typeof(T), type);
Was it helpful?

Solution

From the comments:

The type that's found by resovledList[typeof(T)] isn't the intended type. Instead, it's RuntimeType. This would be a likely result of calling ResolveType<ISomething>(typeof(Something).GetType()) instead of ResolveType<ISomething>(typeof(Something)):

typeof(Something) is a value of type Type (actually RuntimeType, which derives from Type), so calling typeof(Something).GetType() gives you typeof(RuntimeType).

As it turned out, you were actually calling GetType() somewhere else, but the problem and solution are the same: you shouldn't call GetType() here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top