WCF Services in a Shared Hosting Environment
I’m currently using a relatively well known hosting service for my Silverlight 2 application. The problem that I’ve had in getting the app up and running is that in a shared hosting environment, I have no control over host headers and most of the other settings in IIS. So since my url is https://www.singletrax.com, the ops people also added https://singletrax.com to the host headers for my site.
The problem is the order in which they added them. The www address is the second in the list so when I try to link to my services, I get an exception: Exception has been thrown by the target of an invocation. This is because the service is trying to load the host header index of 0 and there ain’t nuthin’ you can do about it that I’ve been able to find!
Except this:
First, add an AppSetting to your web project:
<appSettings>
<add key="HostIndex" value="1" />
</appSettings>
Next, create two new objects:
using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace MyNamespace.Web.Objects
{
class CustomHostFactory : ServiceHostFactory
{
protected override ServiceHost
CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
int hostIndex =
Convert.ToInt32(ConfigurationManager.AppSettings
["HostIndex"].ToString());
CustomHost customServiceHost =
new CustomHost(serviceType, baseAddresses[hostIndex]);
return customServiceHost;
}
}
class CustomHost : ServiceHost
{
public CustomHost(Type serviceType,
params Uri[] baseAddresses) : base(serviceType, baseAddresses)
{ }
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
}
}
}
Then, in your .svc file, reference the custom host this way:
<%@ ServiceHost Language="C#" Debug="true"
Service="MyNamespace.Web.Services.MyService"
CodeBehind="MyService.svc.cs"
Factory="MyNamespace.Web.Objects.CustomHostFactory" %>
This works well for me. I’d be interested in what other hosting services do. Incidentally, I made the index an app setting because I hope that as traffic increases I’ll be able to afford a dedicated or virtual hosting environment.