The default WCF service factory doesn’t offer much: there is no control over how service instances are created and then disposed after the request has been handled. Fortunately, this is possible with a custom service host factory. Years ago I’ve blogged on creating WCF hosts programmatically and today I am going to borrow much of those ideas.
The goal is to have a full control: the service host should allow me to use an IoC container to resolve my service implementation to inject external components. Also, I would like to have an explicit disposal moment so that external components could be disposed when the service is disposed by the host.
We will need three core components: a service host factory, a service host and an instance provider. These three can be defined anywhere, for example in a shared assembly referenced in a web application project.
Let’s start with a custom service host factory which requires an IoC container and creates a service host.
The service host itself doesn’t do much as it delegates the lifetime management to the instance provider:
The instance provider has a major responsibility here. It uses the IoC to create a service and also it disposes the service when the host is disposed:
With all these three in my toolbox (UnityServiceHostFactory, UnityServiceHost and UnityInstanceProvider) I can have a base host factory class for all my WCF services:
The base service host factory relies on a custom service host factory, configured in the Composition Root. To bind the two, the BaseServiceHostFactory and the UnityServiceHostFactory just set up the provider in your global.asax:
As the provider has been set up, I can finally create my services:
And this is it, the ExampleServiceHostFactory can be used to set up a self-hosted service or to server as a factory for *.svc service in a web application. The idea is quite open to extensions, for example if another IoC container should be used to resolve instances, instead of UnityServiceHostFactory, UnityServiceHost and UnityServiceProvider have your WhateverServiceHostFactory, WhateverServiceHost and WhateverServiceProvider and set up the service host factory provider in the composition root: