When you have a WCF service that is not a singleton, and you want to use non-default constructor, you enter a world of pain. There’s a lot of hoops that you have to go through to plug an IInstanceProvider into the service. Even worse if you have many services. To alleviate the pain, I created a small helper method.
private ServiceHost GetService<TService>( string address, Func<TService> createServiceInstance )
var service = new ServiceHost( typeof( TService ) );
var serviceInstanceFactoryBehavior = new ServiceInstanceFactoryBehavior( () => createServiceInstance() );
var endpoint = service.AddServiceEndpoint( typeof( TService ).GetInterfaces().Single(), this.GetBinding(), address );
endpoint.Contract.Behaviors.Add( serviceInstanceFactoryBehavior );
It is based on few assumptions:
- All service types implement just one contract (which I think you should strive for anyway).
- All services use the same binding.
ServiceInstanceFactoryBehavior plugs a custom IInstanceProvider into the host, that uses the provided delegate to fabricate new instances.
As a sidenote, Castle WCF integration facility can do this (in a much more flexible manner), but unfortunately we can’t use it.