daniloquio
daniloquio

Reputation: 3902

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.

Upvotes: 3

Views: 1789

Answers (1)

CodeCaster
CodeCaster

Reputation: 151604

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

Upvotes: 2

Related Questions