I have a library that needs to respond to exceptions in different ways depending on whether it is running in a Console app, WinForms, AspNet or Windows Service. I have experimented with looking at various properties in the System.Windows.Forms and System.Web namespaces, but I can’t find a reliable way of detecting exactly which kind of application is hosting my library. Has anyone been here before? Does anyone have a reliable solution?
Share
I’d question your design before going down this route but I thought this was an interesting challenge and wanted to see if I could find anyways.
ASP.Net : Check HttpContext.Current is not null. You could also look at System.Web.Hosting.ApplicationManager.GetApplicationManager(), but I’m not sure how this will behave outside of Asp.net
Window Forms: You could try and use System.Windows.Forms.Application.OpenForms, this will return any open forms. An assumption is being made that a windows form application would never not have any forms. Also a console application can also start a win form.
Service: Not sure on this but I’m wondering if you can check the name of the process. There must also be a windows API since the task manager shows when a process is a service (At least on Vista it does)