Steven
Steven

Reputation: 172826

BuildManager.GetReferencedAssemblies equivalent for non-web applications

Compared to AppDomain.GetAssemblies(), BuildManager.GetReferencedAssemblies() (System.Web.Compilation.BuildManager) seems a more reliable way to get the assemblies that are referenced by an ASP.NET application at runtime, since AppDomain.GetAssemblies() only gets "the assemblies that have already been loaded into the execution context of this application domain".

Iterating through all assemblies is an important tool for dynamically registering types at application start-up in your DI container and especially during application start-up, chances are that other assemblies are not loaded (where not needed) yet, and the composition root is the first one that needs them. It is therefore very important to have a reliable method to get the application's referenced assemblies.

Although BuildManager.GetReferencedAssemblies() is a reliable method for ASP.NET applications, I'm wondering: what alternatives are available for other types of applications, such as desktop applications, windows services and self-hosted WCF services?

Upvotes: 15

Views: 3338

Answers (3)

Ahuman
Ahuman

Reputation: 762

This solution is based on @steven's answer. But would work in Web, WinForms, Consoles, and Windows Services.

var binDirectory = String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath) ? AppDomain.CurrentDomain.BaseDirectory : AppDomain.CurrentDomain.RelativeSearchPath;

var assemblies = from file in Directory.GetFiles(binDirectory)
                 where Path.GetExtension(file) == ".dll"
                 select Assembly.LoadFrom(file);

Upvotes: 0

Steven
Steven

Reputation: 172826

The only way I currently see is pre-fetching all referenced assemblies manually, just as the BuildManager does under the covers:

var assemblies =
    from file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory)
    where Path.GetExtension(file) == ".dll"
    select Assembly.LoadFrom(file);

Upvotes: 12

jgauffin
jgauffin

Reputation: 101166

I've had the same problem. And after doing some research I've still not found a solid answer. The best I've come up with is to combine AppDomain.CurrentDomain.GetAssemblies() with the AppDomain.AssemblyLoad event.

In that way I can process all already loaded assemblies while getting notified for all new assemblies (which I then scan).

Upvotes: 2

Related Questions