Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Request all implementors of an interface

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?

Walt
Tuesday, May 18, 2004

Yes - read the docs on "Reflection". You should be able to use Assembly.Load(), then GetTypes() on the assembly followed by GetInterfaces() on the Type.

Duncan Smart
Tuesday, May 18, 2004

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[i]);
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[i] = (IFileParser) listParsers[i];

Walt
Wednesday, May 19, 2004

I would use foreach instead of your 1st and 2nd "for" loops, and use ArrayList.Copy instead of your 3rd "for" loop.

Christopher Wells
Wednesday, May 19, 2004

also note that this won't find implementors who are outside of the assembly you've loaded. not sure if that matters to you.

Aaron Boodman
Monday, May 24, 2004

*  Recent Topics

*  Fog Creek Home