BuildManager.GetReferencedAssemblies equivalent fo

2020-06-02 01:56发布

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?

3条回答
SAY GOODBYE
2楼-- · 2020-06-02 02:27

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);
查看更多
混吃等死
3楼-- · 2020-06-02 02:27

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);
查看更多
爷、活的狠高调
4楼-- · 2020-06-02 02:33

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).

查看更多
登录 后发表回答