BuildManager.GetReferencedAssemblies equivalent for non-web applications

你。 提交于 2020-01-01 02:09:05

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/12779665/buildmanager-getreferencedassemblies-equivalent-for-non-web-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!