WCF’s Instance Context model allows me to specify my service’s instantiation behavior – I can get a new instance for every call, have WCF manage a session for me and keep an instance per session, or just get lazy and have my service instantiated as a singleton object and use the same instance forever and ever. Juval Lowy covered the basics of these features here.
I had a Singleton service defined, exposing several Operations through two different endpoints. After some testing, I noticed that every time a call was received on one of the interfaces the constructor would be called again – my singleton was getting dumped and recreated.
It turns out the operation that was causing the problems was marked like this:
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
Since the transaction behavior was the only lead I had, I started to look into it and checked out the other properties of the OperationBehavior attributes. I found the following attribute: (Warning: Links point to a local MSDN installation)
The MSDN documentation for ReleaseInstanceMode, however, mentioned the following tidbit of information:
In transaction scenarios, the ReleaseInstanceMode property is often used to ensure that old data associated with the service object is cleaned up prior to processing a method call. You can also ensure that service objects associated with transactions are recycled after the transaction successfully completes by setting the ReleaseServiceInstanceOnTransactionComplete property to true.
This led me to the ServiceBehavior’s ReleaseServiceInstanceOnTransactionComplete property which set a more general setting that automatically recycled my service instance whenever a transaction completed successfully. Unlike the ReleaseInstanceMode property, this one is by default set to True, meaning that my transactional operation always released my Singleton instance after each successful run.
The moral of the story? The usual. Always check default values, especially on WCF’s Behavior attributes that have lots and lots of properties. Good luck.