Thursday, April 21, 2011

How to get configuration for WCF Service

I want to check whether the endpoint is defined in the configuration before I'll try to create it

System.ServiceModel.ClientBase<T> sourceClient = new System.ServiceModel.ClientBase<T>(EndpointName, new EndpointAddress(discoveryUri));

To check it I need get a configuration but how can I define whether I need to use WebConfigurationManager or ConfigurationManager. Is there any way to define where a WCF service is hosted?

From stackoverflow
  • 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.

0 comments:

Post a Comment