Search code examples
.netwcfwindows-servicessingletonshared

WCF InstanceContextMode.PerCall, shared data between calls


How can I have shared data between instances of a WCF service, when using InstanceContextMode.PerCall, I need to have a shared list that instances will write and read to?

EDIT

Using @usr idea I created a singleton class that has a Queue where the WCF service will register its messages, and in the singleton class I have a running thread that will consume messages from the queue, producer/consumer problem.


Solution

  • Maintain your shared data in a different class than the service class and have your service class be stateless. The stateless service can obtain the singleton instance and use it.

    Here's a sketch:

    class MySingleton {
     //You can use any lazy initialization logic you like
     //I just used a static initializer as an example
     public static readonly MySingleton Instance = new ...();
    
     //Move all static data into this class
     //Use it from anywhere you like
    }
    
    class MyWcfService {
     //This WCF service has no state
     //Any instancing mode will do
     public void SomeServiceMethod() {
      MySingleton.Instance.DoSomething();
     }
    }
    

    This has nothing to do with the question: Stateful web-services and web-apps are to be avoided. You must assume that the application is killed at any time (for example a power failure, crash, bug, ...). Also, you need a high availability solution which usually involves instantiating the application multiple times.