Returning to an object from Assembly.LoadFrom () in C #

I'm trying to create an extension install for this game I'm developing (won't go into details), but each extension will require a .dll file added to the Expansions

I added folder .

I figured out how to access these .dlls added to this folder like below:

Assembly ExpAssembly = Assembly.LoadFrom("Expansions/Intrique.dll");
Type myType = ExpAssembly.GetTypes()[0];

      

Here's an example of the class I'm trying to load:

public class Expansion: MyGame.Expansion {
    public Expansion() {
         //Stuff
    }
    public string SomeMethod()
    {
        return "Test";
    }
}

      

Calling the following code runs SomeMethod () just fine

MethodInfo Method = myType.GetMethod("SomeMethod");
object myInstance = Activator.CreateInstance(myType);
MessageBox.Show(Method.Invoke(myInstance, null).ToString());

      

But I want to write Expansion expObj;

and assign it by calling new Expansion()

from that unspecified reference .dll but not in the library itself.

+3


source to share


1 answer


(For the purposes of this answer, I am assuming your subclass Expansion

is fully qualified Intrique.Expansion

. That is, the namespace is the same as the DLL name).


Since your main program does not reference Intrique.dll, the code in your main program cannot directly use the types in that DLL. That is, Intrique.Expansion

it is not a usable type in the context of your main program's written code, although it can be used at runtime.


Taking your example code literally, the only approach that might work, given the code you are currently using, would be using dynamic

:

dynamic myInstance = Activator.CreateInstance(myType);

myInstance.SomeMethod();

      

This is because it is SomeMethod()

only declared in Intrique.Expansion

. There is no other type that you could statically use in your main program where this method is known.




If this method were instead an implementation of some interface that Intrique.Expansion

your main program implements and belongs to, or there was override

some member virtual

MyGame.Expansion

(which presumably belongs to your main program, if it doesn't actually declare), then you can cast the instance to the interface type or, MyGame.Expansion

accordingly, and call the method like this:

ISomeInterface myInstance = (ISomeInterface)Activator.CreateInstance(myType);

myInstance.SomeMethod();

      

or

MyGame.Expansion myInstance = (MyGame.Expansion)Activator.CreateInstance(myType);

myInstance.SomeMethod();

      


Finally, given that you are trying to implement some kind of extensibility architecture, you might want to consider using the Managed Extensibility Framework , which is designed specifically to handle a lot of the dirty parts of just this kind of thing.

+3


source







All Articles