Suggestions regarding reflection and dynamic load of controls

B

bz

Hi,

how can I inspect programatically, in my app, what classes are
implemented into a dll? I need to know what classes are, and if they
implement a specific interface, I need to be able to load that class
dynamically


E.g. someone creates a dll which implements a certain interface
defined in my framework, and put it into a folder of my app.
then I detect that dll was copied there (with filesystemwatcher) and
if the dll contains a class that implements my interface, to be able
to load it.


can anyone point me into right direction to accomplish this?


Thanks
 
J

jwinn

Assembly.GetTypes() comes to mind, it's in the System.Reflection namespace.
Get the types from the assembly and enumerate or loop through the array it
returns.

foreach (Type currentType in Assembly.GetExecutingAssembly().GetTypes()) {
// Grab the interfaces that the current type implements.
Type[] interfaces = currentType.GetInterfaces();
if (interfaces == null || interfaces.Length == 0) continue;

foreach (Type interfaceType in interfaces) {
if (interfacesType == typeof(MyInterface)) {
// The current type in the assembly does implement the interface
you're looking for. Do with it what you will.

// This will create a new instance of the current type being
checked for the interface.
object obj = Activator.CreateInstance(currentType);
break;
}
}
}

The Assembly.GetExecutingAssembly() method returns an instance of the
assembly that called the method, not the assembly that is the current
executable. If you use this from a DLL project you've referenced in your
executable, it will return the DLL assembly. The GetCallingAssembly and
GetEntryAssembly methods are others you can use to get a different assembly
if you need to.

Granted I haven't tested the code, but it should be something similar to
that. If you're trying to test an assembly that isn't the current assembly
you'll need to load the Assembly and go from there.

Hope that helped.

- Jeff
 
R

Rory Becker

Hi Bz

Regarding jwinn's answer...

...We do exactly this.

We scan every dll in the executing directory looking for classes that have
a certain ancestor class and then record these classes in an xml config file.


The process need not be repeated on the second run as the classes have been
found by this stage and the info stored in the config file is enough to instantiate
the classes in question.

We recreate the config files if we find a dll in the directory with a modified
date greater than than of the config file.

Hope this helps
 

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