Microsoft WCF Gotcha

As a WCF newbie, I experienced some wheel-spinning with a service this week. Here’s a gotcha that made us swerve into the weeds, along with the solution we implemented.

Our team gained traction developing and running a WCF service under our local Cassini web servers.

Our service was performing as expected.

Well, it works fine locally…

Yet we skidded into the ditch when we deployed our service out onto our IIS web servers. Under IIS, we got the cryptic

This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.

Solution

Our solution was to write a Custom Host Factory that overrides the method CreateServiceHost the framework calls when firing up a WCF service.

A custom host class was derived from the framework’s ServiceHost with an override whose purpose is to select the appropriate host vis-a-vis the http context of the server environment (e.g., Dev, QA, Prod).

IIS typically returns a handful of base addresses reflecting any host headers it might have in the Uri array baseAddresses (see above). One of those addresses has to be selected for use. If not, IIS will return the error above. If an appropriate host is not found, a warning is logged to the Windows event log and a default host address returned.

We created the method GetContextAwareAddress to loop through the base addresses IIS returns until we match it with the host of our current http context — HttpContext.Current.Request.Url.Host.

Remember to wire up the custom service factory in the code-in-front of your service so your service knows to call the overridden, customized CreateServiceHost method.

In our case, the service class is named ProductService.svc.cs and the factory is named ProductServiceFactory as shown above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s