Take the 2-minute tour ×

I am reading Juval Löwy's Programming WCF Sevices. It mentions:

In WCF, we have Context in which we have the instance. By default, the lifetime of the context is the same as that of the instance it hosts. We can have separate lifetimes for both. WCF also allows a context to exist without an associated instance at all.

Why would we release the instance and keep the context empty?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Coincidentally I recently read the chapter you're probably referring to. In his book Löwy explains why this may be useful. First he writes:

WCF also allows a context to exist without an associated instance at all. I call this instance management technique context deactivation.

After mentioning this is typically done using an OperationBehavior with a specific ReleaseInstanceMode, he goes on and hints on when you could use this:

You typically apply instance deactivation on some but not all service methods, or with different values on different methods. [...] The reason you typically apply it sporadically is that if you were to apply it uniformly, you would end up with a per-call-like service, in which case you might as well have configured the service as per-call.

So you can use this "deactivation" to ensure only certain methods in a service with sessions behave as if they were part of a per-call service. The abovementioned MSDN article also explains this, in a different wording:

Use the ReleaseInstanceMode property to specify when WCF recycles a service object in the course of executing a method. The default behavior is to recycle a service object according to the InstanceContextMode value. Setting the ReleaseInstanceMode property changes that default behavior. 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.

share|improve this answer
add comment

Disconnecting the context from the instance makes sense when:

  1. Instance creation is customized/extended. For example if you are creating your service instance with a custom IInstanceProvider with a dependency injection library (for example Unity) you might want a Unity lifetime manager to handle the service instance lifetime.

  2. Some but not all operations result in an expensive service instance to be invalidated. For example: The service object loads a large expense resource as a part of creation. If the service operations called by the client modify or invalidate the resource, it needs to be disposed and reloaded for the next caller. If the operations don’t invalidate the resource the service instance can be reused by the next caller. (In almost all cases there’s a better way to solve this problem, but WCF allows it).

I’m sure there are additional use cases.

share|improve this answer
add comment

Your Answer


