简体   繁体   中英

How to check if the context is a Windows Service or a Console Application

Fill the blank:

If a piece of code on a DLL is used from different contexts and we need to identify which context are we running on, we have to use:

Web Application -> System.Web.HttpContext.Current != null

WCF Web Service -> System.ServiceModel.Operationcontext.Current != null

Windows Service || ConsoleApp -> ______________________________________________________

Also, if you know a better option for checking one of the first two, tell us please.

About the fact that it could be a duplicate from another question : I don't need to differentiate between a windows service and a console application (user interactive or not).

EDIT: Why do I need that?

I need to open the configuration file for the running application from a library that can be running on different contexts. This is what I currently have:

Configuration appConfig = null;

if (System.Web.HttpContext.Current != null || System.ServiceModel.OperationContext.Current != null)
{
    // The call was originated from a web application or from a WCF web service.
    appConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
    // The call may have been originated from a console application or a windows service.
    // THE ANSWER TO MY SO QUESTION WOULD ALLOW ME TO INSERT AN IF HERE!!
    appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}

The else part is assuming I'm running on a exe like environment (windows service, console app). I would like to include an if there to be sure that OpenExeConfiguration won't throw an exception.

I already considered using try blocks but that's not suitable for my case.

I think it is a pretty fragile construction, but if you check whether AppDomain.CurrentDomain.SetupInformation.ConfigurationFile ends in the string web.config you can verify that the current application domain is running in a web server, so then you can call System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); to obtain a Configuration instance.

The reverse is true as well: if it ends in .exe.config you can use ConfigurationManager.OpenExeConfiguration(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM