The lifecycle of WCF service hosted in IIS
.net, c#, singleton, wcf
Solution
Checked issue in my local IIS.
This is my code.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service : IService
{
public static int _counter = 0;
public string GetData()
{
_counter++;
return _counter.ToString();
}
}
With default IIS configuration one process is run per application pull and this code works as expected. Result is incremented in every service call.
This makes sense because `InstanceContextMode` does not manage threading. It only controls lifetime of `InstanceContext` lifetime.
Knowing that we still cannot consider using static variables for mutable data as best practice. IIS could be configured as "Web Garden". That configuration means that more than one working process is permitted per application pool and every process will have its own copy of static variable.
http://www.iis.net/ConfigReference/system.applicationHost/applicationPools
How can I make some object to be available for all WCF client calls? Is it possible to do that in IIS or should I host the WCF service in a windows service?
Objects should be stored in persistent storage like database or distributed cache. IIS still remains to be a great host for services and it provides everything that windows service can do plus much more.
Problem
The question is regarding the static data in a class. If that is a service class then I think the instantiating mode is important. But what happens if I have another standalone singleton class? Can I create an object there which will be available for all per-call calls? Does the IIS have that dll in memory forever so that the singleton will be all the time in memory? How can I make some object to be available for all WCF client calls? Is it possible to do that in IIS or should I host the WCF service in a windows service?