.net console app lifecycle - working around a pre-start initialization error from BuildManager.GetReferencedAssemblies

走远了吗. 提交于 2019-12-02 06:52:55
Cerebrate

BuildManager.GetReferencedAssemblies() from the System.Web.Compilation namespace?

So far as I am aware, that's ASP.NET specific, which is why it won't work in your console app. (Or in a Windows app either, for that matter.)

So, the first sub-question is whether or not you need the special functionality of BuildManager.GetReferencedAssemblies, namely, that it grovels through and finds - in addition to ASP.NET specific ways of referencing assemblies - not only all the assemblies that your application references, but all the assemblies that they reference, etc., etc.

(See Difference between AppDomain.GetAssemblies and BuildManager.GetReferencedAssemblies )

If what you're trying to do will work fine with just a list of the assemblies your .exe references directly (plus any that have been dynamically loaded since then, either explicitly by your code or implicitly by calling into a referenced assembly that itself references them), the easiest way is just this:

// Get all currently loaded assemblies.
var assemblies = AppDomain.CurrentDomain.GetAssemblies();

If not, that's where it's going to get complicated for you, because there isn't a straightforward way in .NET to get a list of all assemblies which an app references indirectly. You can, in theory, write code to recursively call Assembly.GetReferencedAssemblies() on Assembly.GetEntryAssembly(), and then on all the results you get from that, and then on all the results you get from those - discarding duplicates so you don't end up in an infinite loop - and you'll eventually end up with all the assemblies that are directly or indirectly statically referenced by your app.

(If you ever reference assemblies dynamically, say by AppDomain.Load() or some such, it won't list them. But then, I don't believe BuildManager.GetReferencedAssemblies() does either.)

AppDomain.CurrentDomain.GetAssemblies() didn't quite do the trick. There were some assemblies that were not included, though they were referenced. What I did was this:

allAssemblies = (from name in Assembly.GetEntryAssembly().GetReferencedAssemblies()
        select Assembly.Load(name)).ToList();

This didn't return as many assemblies as AppDomain.CurrentDomain.GetAssemblies(), but it returned the ones I needed. Not sure why there was a discrepancy. Cerebrate, thank you for the reply though. You got me on the track I needed, and I upvoted your reply.

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