views:

119

answers:

3

I have a class that needs to get some settings from the application configuration file and that is used in a console based app and a web app.

Other than catching an exception how can I determine whether to use:

ServiceModelSectionGroup serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));

or

ServiceModelSectionGroup serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~"));
+1  A: 

While I'm not familiar with exactly what you're trying to do, my guess is that there's a way to get the config section without explicitly specifying what config to use (app.config vs. web.config). Like you can use ConfigurationManager.AppSettings to retrieve values regardless of whether or not your app is a web app, could you use ConfigurationManager.GetSection("system.serviceModel")?

If that doesn't work, I guess the easiest thing would be to simply check if System.Web.HttpContext.Current is null (make sure to add a reference to System.Web), then you can pick which config to use.

wsanville
+3  A: 

I've poked around and it seems you cannot do what you wish because the web model is different from the application model. Somewhat surprising that they don't offer the usual case for this.

I'd add a Configuration parameter to your class's constructor and inject the dependency from the calling code.

roufamatic
A: 

You can check HttpContext, but there are instances when you are hosting WCF services where depending on where you are making the call you won't see an HttpContext. To do this I usually check the hosting process to see if it is IIS or Cassini - the gotcha with that approach is having to worry about updating the library when new OS versions or new versions of VS come out.

HintonBR