0

I am searching through assemblies to identify any classes that implement a desired generic interface so I can dynamically instantiate an instance. This is the code I'm using:

var types = assembly.GetTypes();
var assemblyFormatters = types.Where(type => type.GetInterfaces().Any(i => 
   i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IInterface<>)));

The code works for a standard class:

public class Implementation : IInterface<object>

but not for a generic class:

public class GenericImplementation<T> : IInterface<T>

Event stranger, the code works successfully when run in the intermediate window, but not when run within a unit test framework. The immediate window returns 2 types, the test code run under the debugger returns only the non generic implementation.

I would expect both types to be returned by the code

  • If the code works, then it works. The problem is the unit test project I guess. Does that project have the correct references? – DavidG Apr 16 '19 at 10:37
  • I thought so. Turns out that I was loading in assemblies from `Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)`, which gave the same assembly, but due to the way they were loaded the assemblies were different. I've moved to using `AppDomain.CurrentDomain.GetAssemblies()` which has resolved the issue. I will add it as the answer below – Tom Oliver Apr 16 '19 at 13:51

1 Answers1

0

Turns out it is an issue with assemblies. I was loading in the assemblies using:

var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
foreach (var assembly in Directory.GetFiles(path, "*.dll"))
{
    Assembly.LoadFile(assembly);
}

When comparing the loaded assembly with Assembly.GetExecutingAssembly(), the assemblies are not equal. Since types have references to their respective assemblies, the types were therefore not equal. Moving to use AppDomain.CurrentDomain.GetAssemblies() solved the problem, as I was loading assemblies already loaded by the application.