Wednesday, March 24, 2004 - Posts

Finding the Class that Implements an Interface

I have a program that performs a process I will call ClientProcess1.  This process is run for many different clients.  Most clients need the generic version of ClientProcess1, but some clients need something special.  Because new clients are being added all the time, there is no way to predict all the different variations of ClientProcess1 that might be needed.  To address this, I decided to provide a generic version of ClientProcess1, but to allow other versions of this process to be dynamically loaded as needed.

All versions of ClientProcess1 must implement an interface I will call ClientInterface.  Any custom versions of this process will exist in separate assemblies.  Each client can be configured with a path to an assembly that includes a specialized version of ClientProcess1.  I show how I dynamically load the specified assembly in a previous post.  Here is how I determine which class in this assembly I should call.

Assembly asm = Assembly.LoadFile("C:\\ProgramDirectory\\CustomAssembly.dll");

foreach (Type t in asm.GetTypes())
{
      Type[] Interfaces = t.FindInterfaces(new TypeFilter(MyInterfaceFilter),"MyNamespace.ClientInterface");

      if (Interfaces.Length > 0)
      {
            ClassToInstantiate = t;
        
    break;
      }
}

You need a delegate that determines how to compare your interfaces.  Here is the one that I use.

public static bool MyInterfaceFilter(Type typeObj,Object criteriaObj)
{
      if(typeObj.ToString() == criteriaObj.ToString())
            return true;
      else
           
return false;
}