Question

Does setting AssemblyName.CodeBase force the assembly to be loaded in the LoadFrom context?

I'm working on a kind of plugin system. I need to be able to use Type.GetType etc... At any place in my code I should not have to know if the Type come from a plugin dll or not.

My plugins are in a folder Plugins under the bin directory of my application (windows/web) and each plugin is in it's own folder.

I set my probing path to Plugins (or bin;bin\Plugins for web) even if it doesn't make any difference since they are in sub folders.

And I load my Plugin like this

pluginInfo.EntryAssemblyName = new AssemblyName(myAssemblyName);

pluginInfo.EntryAssemblyName.CodeBase = assemblyPath;

pluginInfo.EntryAssembly = Assembly.Load(pluginInfo.EntryAssemblyName);

Note: PluginInfo is just a class that keep the state of my plugin.

I wondering, because I set the CodeBase property of the assembly name Assembly.Load is able to find my assembly even if its not in the probing path, does it mean that the assembly get loaded in the default context or the load from context?

Is it normal that the AssemblyResolve event is raise after for the entry assembly again?

Was it helpful?

Solution

By using the AssemblyName(string) .ctor and setting the AssemblyName.CodeBase property, you cannot be sure that Assembly.Load(AssemblyName) will load it in the default context. It will first try to load it in the default context but if this fails, it will use the codebase to load it in the LoadFrom context. Have a look at Suzanne Cook's blog entry on the subject for more information.

To be sure that the assembly will be loaded in the default context, do not set the AssemblyName.CodeBase property and be prepared for a System.IO.FileLoadException. If the object is constructed successfully (no exception is thrown), then the assembly was loaded in the default context.

The advantage of the LoadFrom context is that the dependencies of the loaded assembly can be resolved if they exist on the same path. On the other hand, assemblies loaded on the default context can be resolved only if the exist on the GAC, the AppDomain.BaseDirectory or the AppDomain.RelativeSearchPath. The AppDomain.AssemblyResolve event is probably raised because a dependency of the loaded assembly cannot be found in these loactions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top