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
When WCF service is configured for Singleton instance mode, all clients are independently connected to the same single instance. This singleton instance will be created when service is hosted and, it is disposed when host shuts down. Following diagram represent the process of handling the request from client using Singleton instance mode.
The service is implemented as both a Windows Service and as a WCF service by causing it to inherit from the ServiceBase class as well as from a WCF service contract interface. The ServiceHost is then created and opened within an overridden OnStart (String []) method and closed within an overridden OnStop () method.
This hosting option consists of registering the application domain (AppDomain) that hosts a WCF service as a managed Windows Service (formerly known as NT service) so that the process lifetime of the service is controlled by the service control manager (SCM) for Windows services.
Open it and go to the SSL tab, click Add, enter the IP address of your WCF Service, the port, the GUID of the Windows Service found in AssemblyInfo, and then Browse for the certificate you just created. Click OK and then Apply, and your WCF Service should work now over secure HTTPS.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With