jeudi 6 avril 2017

Assembly.GetTypes() does not return types that implement an interface defined elsewhere

I am working to create a list of all implementations of a specific interface in my application and I'm trying to do this by reflection in a T4 Template, using it to generate C#.

I have some code that looks like this:

<#@ assembly name="$(SolutionDir)\..\Project2\bin\project1.dll" #>
<#@ assembly name="$(SolutionDir)\..\Project2\bin\project2.dll" #>
<#@ import namespace="Project1.Interfaces" #>
<#
    string assemblyPath1 = this.Host.ResolvePath("..\\Project2\\bin\\project1.dll");
    string assemblyPath2 = this.Host.ResolvePath("..\\Project2\\bin\\project2.dll");
    var type = typeof(Project1.Interfaces.IAction);
    var types1 = Assembly.LoadFrom(assemblyPath1).GetTypes()
                .Where(p => type.IsAssignableFrom(p) && p.IsClass).ToList();
    var types2 = Assembly.LoadFrom(assemblyPath2).GetTypes()
                .Where(p => type.IsAssignableFrom(p) && p.IsClass).ToList();
#>

Obviously the real version does a lot more and you can assume that if you can't see an import directive I have omitted it here for brevity and readability. but as far as I can tell this is where the problem arises. The types1 variable will contain a list of a whole lot of IAction implementations, but the types2 list will be empty, in spite of the fact that I have Project2 open right in front of me and it definitely contains several public types that implement IAction .

From what I can tell looking at the documentation, this is probably because the IAction interface is defined in Project1 and there can be problems with GetTypes() related to assemblies being loaded when it is called. However, as far as I can tell the actual call is running smoothly- I'm not seeing a ReflectionTypeLoadException being thrown - it just does not find those interface implementations. If I list the names of everything returned in the types2 collection, those class names are absent from the list.

What do I need to do in order to be able to find the implementations of the IAction interface in my second assembly?





Aucun commentaire:

Enregistrer un commentaire