lundi 20 mars 2017

How to test if assembly contains class implementing an interface?

Okay, I'm trying to implement a dynamic module loader for a .NET Core app. The modules are class libraries that may or may not contain a Startup.cs with a class that implements an IModuleInitializer interface. I look through the modules for the initializer class and create an instance of it if it exists. This worked fine until a recent .NET Core update. Now I can't figure out how to test if a type implements the IModuleInitializer interface.

Here's my code:

private static IModuleInitializer CreateModuleInitializer(Assembly assembly)
{
    Type moduleInitializer = null;
    foreach(var type in assembly.GetTypes())
    {
        var interfaces = type.GetTypeInfo().ImplementedInterfaces;
        var interfaceType = typeof(IModuleInitializer);
        var result = interfaces.FirstOrDefault() == interfaceType;
        var result1 = interfaces.Contains(interfaceType);
        var result2 = typeof(IModuleInitializer).GetTypeInfo().IsAssignableFrom(type);
        if (interfaces.Contains(interfaceType))
        {
            moduleInitializer = type;
            break;
        }
    }

    if (moduleInitializer != null && moduleInitializer != typeof(IModuleInitializer))
    {
        return (IModuleInitializer)Activator.CreateInstance(moduleInitializer);
    }

    return null;
}

Here's a screenshot of the values when I debug to a type that implements the interface: enter image description here

And my .NET Core version info in case it helps:

C:\Users\Jason>dotnet --version
1.0.1

C:\Users\Jason>dotnet --info
.NET Command Line Tools (1.0.1)

Product Information:
 Version:            1.0.1
 Commit SHA-1 hash:  005db40cd1

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.14393
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\1.0.1

Any ideas? I'm really hoping I'm just doing something dumb.





Aucun commentaire:

Enregistrer un commentaire