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
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.