vendredi 5 février 2016

Type.GetType() by string from an already loaded assembly [duplicate]

This question already has an answer here:

I've got a small plugin architecture where I load plugins from a custom directory using MEF. For some requirements, I need to create an instance of a Type from a class which is contained within one of the plugin assemblies. I'm trying to do this using Type.GetType() and the fully qualified name of the type (assembly + namespace + type).

This fails because .NET somehow tries to load the type from the assembly which (obviously) isn't contained in the default probing paths of the executable. This behavior would be fine if the type isn't present yet, however since I already loaded the whole assembly ealier (remember, plugin framework), the assembly in question is already loaded into the current app domain! When I create an instance of the Type class in the plugin and return it through some contract, I can use it without any problems.

How can I tell the .NET runtime that it shouldn't load the type from an assembly, but check if the assembly hasn't been already loaded in the current app domain first?

Classes to reproduce the problem (half-pseudo):

// --- MyProject.Contract
public interface IPlugin {
    string GetTypeName();
    Type GetType();
}

// --- MyProject.Plugin
public class SomeType { }

public class MyPlugin : IPlugin {

    public string GetTypeName() {
        return typeof(SomeType).AssemblyQualifiedName;
    }

    public string GetType() {
        return typeof(SomeType);
    }

}

// --- MyProject.App
var assembly   = Assembly.LoadFrom("path/to/pluginfolder/MyPlugin.dll");
var pluginType = assembly.GetExportedTypes().OfType<IPlugin>().FirstOrDefault();
var plugin     = (IPlugin) Activator.CreateInstance(pluginType)

Console.WriteLine(plugin.GetType().Name); // works

// fails because .NET tries to load the assembly AGAIN and doesn't find it
// in the default probing paths
Console.WriteLine(Type.GetType(plugin.GetTypeName()));

Oh, and btw: I'm not looking for a solution like e.g. resolving assemblies manually or adding additional probing paths. I want to prevent .NET from being stupid and check the loaded assemblies for the type in question before trying to load an assembly.





Aucun commentaire:

Enregistrer un commentaire