Reputation: 37
I am currently studying WCF sessions and after reading few articles on MSDN... one thing that I feel confusing is about Clear Difference between SessionMode and InstanceContextMode that we can use in WCF.
I know the different values that we can use for both these attributes but what exactly is the difference between these two methods?
Why there are these two methods in WCF?
Upvotes: 1
Views: 811
Reputation: 23
Actually there is a difference between these two methods. The SessionMode
is a property of the ServiceContract
attribute. The ServiceContract
attribute should be applied to interfaces. Whereas the InstanceContextMode
property is a member of the ServiceBehaviour attribute, which is applied on the actual implementation of a service (class).
So with the SessionMode
property you define wich type of SessionModes are allowed to be implemented on the actual service. And with the InstanceContextMode
property you define the actual implemented behaviour of a service.
If the interface is marked with SessionMode.NotAllowed
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface IHelloService
{
[OperationContract]
string SayHello();
}
And the class is marked with InstanceContextMode.PerSession
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class HelloService : IHelloService
{
private int _requestCount;
public string SayHello()
{
_requestCount++;
return $"Hello this is your {_requestCount} request";
}
}
A System.InvalidOperationException
will be thrown at runtime once you try to host the Service.
Remark: A weird thing I experienced. When you mark the interface with SessionMode.Required
and mark the class with InstanceContextMode.PerCall
, no exception is thrown and everythink works fine. Can anyone explain me why?
Upvotes: 1
Reputation: 7067
While the two values seem similar and in some ways interact, the settings actually control different aspects of the WCF
service. The InstanceContextMode
property is used to control when new service objects are created by the application. The SessionMode
, on the other hand, indicates whether sessions are allowed, not allowed, or required.
Some additional links to review:
https://msdn.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.sessionmode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.instancecontextmode(v=vs.110).aspx
Upvotes: 0