C# – How does one set up a WCF ServiceHost within a Windows Service that can access stateful information within the Windows Service

c++servicehoststatefulwcfwindows-services

I have a written a Windows Service in C#. It is functioning and performing well. I have added a WCF service to the Windows service to enable client applications to connect to the Windows service and obtain stateful information from the Windows service.

I configured the WCF service to be a singleton, so that the same service instance is used to handle all requests from all clients as follows:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

All clients are able to connect and have access to the same stateful information within the WCF service. However, I am running into the following peculiar behavior.

Revised:
I instantiate the WCF service contract within my Windows Service. Any stateful information assigned at the time of instantiation is available to all clients that connect to the service.

However, any stateful information added to the service contract instance later directly from the Windows Service (not by clients) is not visible to clients that connect to the service. It is as if there are two instances of the service contract: One for the Windows Service and one for the clients that connect to the WCF service.

What is the recommended (best) way to instantiate a WCF service and have it be able to access stateful information available within the Windows Service?

Best Solution

I would recommend doing an end-run around this by holding your state in a static member, so that it doesn't matter whether or not WCF is creating a new instance for each call or reusing one. This solves the problem and simplifies the code.

Related Question