Instantiating an object of a type identified by reflection

4

42

Hi,

I've got a little blurb of code (part of a plugin architecture):

public IPlugin CreateInstance(string assemblyPathName, string className)
{
// Load Assembly
Assembly theAssembly = Assembly.LoadFrom(assemblyPathName);

// Get Class
Type theClass = theAssembly.GetType(className);

// Call Constructor
IPlugin plugin = (IPlugin)theClass.InvokeMember(
null,
BindingFlags.CreateInstance,
null,
null,
null);
return plugin
}

It works perfectly, but the constructor call seems clumsy. Is there a
more direct way? I feel like I've gone the long way around...
like I called the c++

z = x.operator +(4);

instead of just the natural

z = x+4;

....

e.g. I feel like I should somehow be able to write:

plugin = new theTypeClass();

or

plugin = theTypeClass.GetInstance();

Anyhow... just wanted to check whether I've done it the 'right' way. As
I said it works; but it looks over-wrought.

(As an aside, the assemblypathname, and classname are enumerated in an
earlier part of the program which scans the plugin folder for dlls with
public, non-abstract classes that that implement IPlugin... this also
struck me as odd -- again I just have this inkling that there should be
a way of querying an assembly for instantiable classes with a given
interface without rummaging through its "private" parts. Have I missed
something there too?)

-regards,
Dave
 
I

InK_

Hi

try Activator.CreateInstance(...)
e.g. this one:
public static ObjectHandle CreateInstance(
string assemblyName,
string typeName
);
 
Top