Create a dynamic instance of a object that implements an interface

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?
 
M

Marc Gravell

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
 
G

Guest

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?
 
G

Guest

Hi MArc,

I have found the answer. I needed the following:
MyInstance = Oh.Unwrap() as IMyInterface;
Sorry to have troubled you!
 
M

Marc Gravell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top