You would have to need to have the information yourself - the WCF service itself doesn't know whether it'll be hosted in IIS or self-hosted. After all, it's just a ServiceHost
instance being spun up some way.
So I guess you'd have to have some setting that you can put into either web.config
or app.config
- something like:
<add key="WCFHost" value="IIS" />
or
<add key="WCFHost" value="CustomApp" />
and then evaluate that value and depending on what you get back, either open WebConfigurationManager or just ConfigurationManager.
You might think you could check for the presence of HttpContext
: if it's NULL, then you're running in a custom app, if it's not NULL, then it's the web scenario. But that doesn't work since you can host a WCF Service in IIS (thus you'd have a web.config
to consult) but without the ASP.NET compatibility settings, in which case, HttpContext
would be NULL even though you're running inside a web hosting scenario.
One option would be to check this setting here:
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
This will contain the full path to the current AppDomain's configuration file - if it's a web app, this will contain a path + web.config
at the end.
So if you check
if(Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) == "web.config")
you can be pretty sure you're in a web app and you have a web.config
to look at.