How to configure WCF service from code when hosted in IIS?

"IIS will take care of spinning up the necessary ServiceHost based on your *.svc file - not a whole lot you can do about that, really."

Not too close to the truth. Exactly in the SVC file of your service there is attribute named Factory. Where you can specify the the class and the assebly where the class is located. This class may be your own descendant of Web|DataServiceHostFactory So your svc markup would look like this

<%@ ServiceHost 
Language="C#"
 Debug="true" 
 Service="name.space.myService" 
 CodeBehind="name.space.myService.svc.sc" 
 Factory = "name.space.WebServiceHostFactoryEx, assembly.name"
 %>

The WebServiceHostFactory will be created for every service hit and will recreate your host the way you want it.

You will also need to inherith WebServiceHost and create it the way you need it with certain endpoins, behaviors, addresses, etc settings - whatever you like.

There is very nice post from Michele Bustamante here

EDIT: I figured out the above link is not working anymore, so here it is another one.

I am using this in IIS hosted enviroment for couple of services that are initialized same way.


When you're hosting in IIS, you're leaving a lot of care taking into the realm of IIS - you cannot really grab a hold of your service in this case.

IIS will take care of spinning up the necessary ServiceHost based on your *.svc file - not a whole lot you can do about that, really.

My solution would be different - externalize the <service> tag in your configuration file (web.config):

<system.serviceModel>
  <services>      
     <service configSource="service.dev.config" />
  </services>
</system.serviceModel>

In your dev environment, only expose the http endpoint - so your service.dev.config would look something like this:

<service name=".....">
    <endpoint name="default"
              address="....."
              binding="basicHttpBinding" bindingConfiguration="insecure"
              contract="......" />
</service>

Create a second service.prod.config which then contains both endpoints - http and https:

<service name=".....">
    <endpoint name="default"
              address="....."
              binding="basicHttpBinding" bindingConfiguration="insecure"
              contract="......" />
    <endpoint name="secure"
              address="....."
              binding="basicHttpBinding" bindingConfiguration="secure"
              contract="......" />
</service>

and reference that in your web.config on the deployment server.