Specify a Singleton service in a WCF self hosted service

Erick T picture Erick T · Mar 21, 2011 · Viewed 10k times · Source

I am writing an application that exposes a service via WCF. The service is self-hosted (console app) and needs to use a Singleton instance. I am trying to figure out how to specify singleton in the service configuration without using attributes on the service implementation. Is it possible to specify singleton in code without an attribute?

Thanks, Erick

Answer

Ladislav Mrnka picture Ladislav Mrnka · Mar 21, 2011

You can pass instance of the service to the ServiceHost constructor instead of passing a type. In such case your passed instance will be used as singleton.

Edit:

My former solution doesn't work. Providing instance to ServiceHost constructor still demands ServiceBehaviorAttribute with InstanceContextMode.Single. But this one should work:

var host = new ServiceHost(typeof(Service));
var behavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
behavior.InstanceContextMode = InstanceContextMode.Single;
host.Open();

ServiceBehaviorAttribute is included even if you don't specify it so you just need to get it and change default value.