Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify a Singleton service in a WCF self hosted service

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

like image 782
Erick T Avatar asked Mar 20 '11 23:03

Erick T


People also ask

What is singleton instance mode in WCF?

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.

How do I implement servicehost in WCF?

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.

What is WCF hosting?

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.

How do I set up a WCF server over HTTPS?

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.


1 Answers

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.

like image 59
Ladislav Mrnka Avatar answered Sep 19 '22 14:09

Ladislav Mrnka