Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force all referenced assemblies to be loaded into the app domain?

My projects are set up like this:

  • Project "Definition"
  • Project "Implementation"
  • Project "Consumer"

Project "Consumer" references both "Definition" and "Implementation", but does not statically reference any types in "Implementation".

When the application starts, Project "Consumer" calls a static method in "Definition", which needs to find types in "Implementation"

Is there a way I can force any referenced assembly to be loaded into the App Domain without knowing the path or name, and preferably without having to use a full-fledged IOC framework?

like image 302
Daniel Schaffer Avatar asked Mar 05 '10 04:03

Daniel Schaffer


People also ask

What is the method to load assembly by name?

Loads an assembly given its AssemblyName. The assembly is loaded into the domain of the caller using the supplied evidence. Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.

Could not load a file or assembly?

Http 5.2. 0.0? In summary if you get the "Could not load file or assembly error", this means that either your projects or their references were built with a reference to a specific version of an assembly which is missing from your bin directory or GAC.

When would using assembly LoadFrom or assembly LoadFile be appropriate?

So, you should use LoadFrom when you need to prevent loading second assembly with same identity or just loading assembly twice. Respectively, you should use LoadFile only if you need to load assembly twice or load two assemblies with same identifier.


1 Answers

This seemed to do the trick:

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList(); var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();  var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll"); var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();  toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path)))); 

As Jon noted, the ideal solution would need to recurse into the dependencies for each of the loaded assemblies, but in my specific scenario I don't have to worry about it.


Update: The Managed Extensibility Framework (System.ComponentModel) included in .NET 4 has much better facilities for accomplishing things like this.

like image 113
Daniel Schaffer Avatar answered Sep 22 '22 06:09

Daniel Schaffer