Request all implementors of an interface

  • Thread starter Thread starter Walter L. Williams
  • Start date Start date
W

Walter L. Williams

I'm not sure this is possible, but is there an elegant way to ask for a list
of objects who implement an interface?

Basically what I want to do is create a top level shell that can query dlls
in its directory for a certain interface. It would be kind of like a
plug-in. I would like a call that returns an array of interface pointers,
so that I could just drop in a new dll and the next time the call is made,
it is included. The shell should not have to change to accomodate new
plug-ins.


I have the following interface:

public interface IFileParser
{
String GetFileFilter ();
Boolean ParseFile (String strFile, AddItemDelegate delegateAddItem);
}

Elsewhere, I want to call something like this:

IFileParser[] arrayFileParsers = GetIFileParserImplementors();


Does the framework provide anything for this or what approaches would be
advisable?
====================================================
Walter Williams
Software Engineer
Sawtooth Software, Inc.
http://www.sawtoothsoftware.com
 
Walter L. Williams said:
I'm not sure this is possible, but is there an elegant way to ask for a list
of objects who implement an interface?

Basically what I want to do is create a top level shell that can query dlls
in its directory for a certain interface. It would be kind of like a
plug-in. I would like a call that returns an array of interface pointers,
so that I could just drop in a new dll and the next time the call is made,
it is included. The shell should not have to change to accomodate new
plug-ins.

Use one of the forms of Assembly.Load* to load the DLL, and then use
Assembly.GetTypes to get all the types within it. From there, use

if (typeof(IFileParser).IsAssignableFrom(typeToTest))

to check whether a type implements IFileParser.
 
It worked! Thanks a lot.

String[] arrayDlls = Directory.GetFiles(Application.StartupPath, "*.dll");
ArrayList listParsers = new ArrayList();
for (Int32 i = 0; i < arrayDlls.Length; ++i)
{
Assembly oAssembly = Assembly.LoadFrom(arrayDlls);
Type[] arrayTypes = oAssembly.GetTypes();
for (Int32 j = 0; j < arrayTypes.Length; ++j)
{
if ((typeof(IFileParser) != arrayTypes[j]) &&
typeof(IFileParser).IsAssignableFrom(arrayTypes[j]))
{
IFileParser oParser = (IFileParser)
System.Activator.CreateInstance(arrayTypes[j]);
listParsers.Add(oParser);
}
}
}
this.arrayParsers = new IFileParser[listParsers.Count];
for (Int32 i = 0; i < this.arrayParsers.Length; ++i)
this.arrayParsers = (IFileParser) listParsers;

====================================================
Walter Williams
Software Engineer
Sawtooth Software, Inc.
http://www.sawtoothsoftware.com
 
Back
Top