David Smith

David Smith

  • NA
  • 2k
  • 0

c# Loading Assemeblies with Specific Interface

Nov 3 2016 4:24 AM
I am trying to only add assemblies to list that implements the IPluginContract interface.
 
Is there a better way to do this logic below.
 

This is what I have so far. Is there a robust way to do this below


private static void LoadPlugins(IList<Assembly> assemblies)
{
DirectoryInfo dInfo = new DirectoryInfo(GetExtensionsDirectory());
FileInfo[] files = dInfo.GetFiles("*.dll");

if (files != null)
{
foreach (FileInfo file in files)
{
string[] fileArray = file.Name.Split('.');

if (fileArray != null)
assemblies.Add(Assembly.Load(fileArray[0]));
}

IList<Assembly> copyAssemblies = assemblies;

foreach (var assembly in copyAssemblies.ToList())
{
foreach (var assemblyType in assembly.GetExportedTypes())
{
int index = assembly.GetExportedTypes().ToList().IndexOf(assemblyType);

var implementsInterface = typeof(IPluginContract).IsAssignableFrom(assemblyType) && assemblyType.IsClass;

//If class assembly does not have IPluginContract, remove assembly from list

if (!implementsInterface && !assemblyType.IsInterface)
{
assemblies.RemoveAt(index);
}
}
}
}
}

 

Answers (1)