Is it possible to determine the type of application a .net component is being called by at runtime?
I'm writing a software component which can be consumed by various .net applications. Is there anyway that the component can become aware of whether its being called by an ASP.Net Windows Forms, WPF, Silverlight application, a WCF serv开发者_开发技巧ice...?
Not really, since an app could use more than one framework. Your best bet is probably to look at which assemblies are loaded into the calling AppDomain, and take it from there :)
As @cwap said, Use AppDomain.CurrentDomain.GetAssemblies()
and check if WinForms or Asp is found.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.Location.EndsWith("System.Windows.Forms.dll"))
Console.WriteLine("Winforms is loaded");
}
About the only reason I can think of why you'd need this info is if you're encountering "Invoke" issues, where you need to be on e.g. the GUI thread of a winforms app.
If that's the reason, then this has been abstracted out by the SynchronizationContext class.
If it's some other reason, it might be helpful for us to know why you need this info. There may be a similar abstraction that has already been created to suit your needs.
精彩评论