Create a dynamic instance of a object that implements an interface

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi All,

I want to create an instance of an object that implements a known interface.
I just want to pass the assembly location and name followed by the class. My
code looks like this:

// The OK part
IMyInterface MyInstance;

System.RunTime.Remoting.ObjectHandle Oh =
System.Activator.CreateInstanceFrom(MyAssembly.dll, MyClass);
// Then cast to instance

MyInstance = (IMyInterface) Oh.CreateObjectRef(???) // Not sure what should
go here

Both MyAssembly.dll and MyClass are strings that give the location + name and
class to use to construct the object instance
MyClass implements IMyInterface
I want to use MyInstance as I would have done had it been early bound.

I just don't know how to urn the handle into an instance of the object.

Any ideas anyone?
 
Look at Activator.CreateInstance(), in particular
CreateInstance(string assemblyName,string typeName)

Alternatively, use Type.GetType() to resolve the Tyupe from an
assembly-qualified name, and use Activator.CreateInstance(type)

Either way, the CreateInstance() returns an object, so simply cast to
IMyInterface:

IMyInterface obj = (IMyInterface)Activator.CreateInstance(...);

Marc
 
Hi Marc,

Thanks for the post. The only overload for CreateInstance() that I can find
with the signature (string, string) returns an ObjectHandle.

Do you have a code example that turns the handle to the object?
 
Hi MArc,

I have found the answer. I needed the following:
MyInstance = Oh.Unwrap() as IMyInterface;
Sorry to have troubled you!
 
No - I'm sorry - my mistake! I incorrectly recalled that it returned
"object" from this overload - I was wrong, and thinking of the Type
overload. Apologies for confusing you.

Marc
 
Back
Top