John
John

Reputation: 1903

The lifecycle of WCF service hosted in IIS

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?

Upvotes: 5

Views: 6884

Answers (2)

Dmitry Harnitski
Dmitry Harnitski

Reputation: 6008

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.

Upvotes: 2

Channs
Channs

Reputation: 2101

Will provide some hints based on the short context you provided

  • If you have a static class, the state is maintained as long as you have access to the same WCF proxy. The host (IIS or Windows service) does not matter.

  • If you want to maintain 'global static variables' across client requests, why don't you store them in a repository (file/database/etc.)?

  • If you want to retain state for each client request, you can look at 'Durable WCF services' a try (related thread). I have used it earlier - so it does work provided your scenario demands session like behavior and is aware of the performance cost.

Hope this helps.

Upvotes: 2

Related Questions