Per-Session Instance Management in WCF

Objective

This article is part # 2 of Instance Management in WCF. This article will explain Session Full Instance management service. This will explain different Session Mode at Contract level. This will explain Per-session service also. This article will be explaining Session Full Service with a code also.

Part # 1 of this series could be found Here

Per-Session Service

 


 

  1. WCF can maintain a logical session between a client and service.
  2. The service instance remains in the memory throughout the session.
  3. The client session is per service endpoint per proxy.

     


     

Configuring Session Full service

There are three elements, which must be taken care while configuring a session full service.

 


 

Behavior Facet

  1. The Behavior part is required, so that WCF will keep the Service Instance Context alive throughout the session.

 

 

  1. InstanceContextMode.PerSession is default value for InstanceContextmode property.
  2. The session terminates when client closes the proxy.
  3. Proxy has to notify the service that session has been closed and service calls the Dispose () method on worker thread. 

Contract Facet

 In order to create all messages from a particular client to a particular instance WCF needs to identify the client and this is done by TRANSPORT SESSION.

 

 

  1. For this ServiceContract attribute having a property called SessionMode.
  2. Type of property SessionMode is enum SessionMode.
  3. It is inside namespace System.ServiceModel.
  4. Property SessionMode is a public property


 

  1. SessionMode enum is default to SessionMode.Allowed.
  2. The Configured value of SessionMode is exposed to client in MetaData.

SessionMode.Allowed

 

  1. When the SessionMode is configured with SessionMode.Allowed, transport session are allowed but not enforced.
  2. The Behavior of service will depend upon behavior configuration and binding.  


Code Example

Both code is same because SessionMode.Allowed is default.


 

SessionMode.Required

 

  1. SessionMode.Required value restricts to use Transport level session. 
  2. If a contract is configured as SessionMode.Required with a service end point who’s binding does not maintain a Transport level session a Run time error will encountered at loading of service. 

     



 

Code Example

SessionMode.NotAllowed 

  1. This disallows the use of Transport session.
  2. Regardless of the service configuration, when SessionMode.NowAllowed is configured at contract, the service will always behave as Per-call service.

     


     

Code Example

[ServiceContract(SessionMode=SessionMode.NotAllowed)]


public
interface
IService1

{

}

Explanation of Per-Session service instance with a Sample

 

Consider code below

Service contract

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

 

namespace PerSessionSample

{

 

[ServiceContract(SessionMode=SessionMode.Required)]


public
interface
IService1

{

 

[OperationContract]


int GetData();

 

}

 

}

 

Service

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

 

namespace PerSessionSample

{

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]


public
class
Service1 : IService1,IDisposable

{


int _counter = 0;


public Service1()

{

 

}


public
int GetData()

{

_counter++;


return _counter;

 

}


public
void Dispose()

{

}

 

 

}

}

Client

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Test.ServiceReference1;

 

namespace Test

{


class
Program

{


static
void Main(string[] args)

{


Service1Client proxy1 = new
Service1Client();


Console.WriteLine(” 1st Output by Proxy 1″);


Console.WriteLine(proxy1.GetData().ToString());

 


Console.WriteLine(” 2nd Output by Proxy 1″);


Console.WriteLine(proxy1.GetData().ToString());

 

 

 

 


Service1Client proxy2 = new
Service1Client();


Console.WriteLine(“1st Output by Proxy 2″);


Console.WriteLine(proxy2.GetData().ToString());

 

proxy2.Close();

 

 


Service1Client proxy3 = new
Service1Client();


Console.WriteLine(“1st Output by Proxy 3″);


Console.WriteLine(proxy3.GetData().ToString());

 

 

 


Console.WriteLine(” 2nd Output by Proxy 3 “);


Console.WriteLine(proxy3.GetData().ToString());

 

 


Console.WriteLine(” 3rd Output by Proxy 1 “);


Console.WriteLine(proxy3.GetData().ToString());


Console.ReadKey(true);

 

 

}

}

}

 

Output


Explanation

  1. We could see from output is that Service Instance is particular and individual for each individual proxy.
  2. When proxy is getting closed or down, service instance is also being disposed on worker thread.

Conclusion

This article was part# 2 of multi series Instance Management Article. This article explained about Session Full Service Management.

Happy Coding

About these ads

Session Id in WCF

Objective 

This article is part # 4 of Instance Management in WCF. This article will explain how to work with Session ID in WCF. This article will give theoretical introduction and explanation of coding sample also. It will explain 2 full coding sample that how to work with Session ID in WCF.

Part # 1 of this series could be found Part 1

Part # 2 of this series could be found Part 2

Part # 3 of this series could be found Part 3 

Note: There is no any attached code with this article because; I have amended same sample to give different demonstration. I am sorry for that, but once you will go through article, you will able to understand the concept behind. 

The Session ID in WCF

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

                                                                                                                                                                                                                                                                                                                          

  1. Every session has a unique Session ID.
  2. Both client and service can obtain and use the Session ID.
  3. The Session ID is in form of GUID.
  4. The main use of Session ID is in logging.


    Session ID at Server side 

  1. Every Service operation has an operation call context accessible via the operational class.
  2. A Service can obtain a reference to the operation context of current method via the Current static method of the OperationConext class.

 

Session ID at client side

 

Fetching Session ID at client for a Per-Session configured service (Sample #1)

In below code sample

  1. Service is configured as Session full service.
  2. SessionMode of contract of service is set to Required.
  3. Client is referencing the service and creating different proxies.
  4. Expected output is , 

     

Service Interface (Contract)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SessionTestingService

{

[ServiceContract(SessionMode=SessionMode.Required)]


public
interface
IService1

{

[OperationContract]


int GetData();

}

}

Service

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SessionTestingService

{

[ServiceBehavior(InstanceContextMode= InstanceContextMode.PerSession)]


public
class
Service1 : IService1

{


public
int GetData()

{


return 9;

}

}

}

Client

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using SessionIdSampleatClient.ServiceReference1;

namespace SessionIdSampleatClient

{


class
Program

{


static
void Main(string[] args)

{


Service1Client proxy = new
Service1Client();

proxy.Open();


string sessionid = proxy.InnerChannel.SessionId;


Console.WriteLine(“Session id of 1st Proxy = “+sessionid);

proxy.Close();


Service1Client proxy1 = new
Service1Client();

proxy1.Open();

sessionid = proxy1.InnerChannel.SessionId;


Console.WriteLine(“Session id of 2nd Proxy = “ + sessionid);

proxy1.Close();


Service1Client proxy3 = new
Service1Client();

proxy3.Open();

sessionid = proxy1.InnerChannel.SessionId;


Console.WriteLine(“Session id of 2nd Proxy = “ + sessionid);

proxy3.Close();


Console.ReadKey(true);

}

}

}

Output



Comparing Session ID at client and Service for a Per-Session configured service (Sample #2)

In below code sample

  1. Service is configured as Session full service.
  2. SessionMode of contract of service is set to Required.
  3. Service is exposing one Operation Contract, which is returning Session ID for a particular operation context.
  4. Client is creating a Proxy and fetching the session ID.
  5. There is a comparison between Session Id returned by service and Session Id fetched by client for a particular session. Whether both session ID is same or not.

Service Interface (Contract)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SessionTestingService

{

[ServiceContract(SessionMode=SessionMode.Required)]


public
interface
IService1

{

[OperationContract]


string GetSessionID();

}

}

Service

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SessionTestingService

{

[ServiceBehavior(InstanceContextMode= InstanceContextMode.PerSession)]


public
class
Service1 : IService1

{


public
string GetSessionID()

{


string sessionId = OperationContext.Current.SessionId;


return sessionId;

}

}

}

Client

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using SessionIdSampleatClient.ServiceReference1;

namespace SessionIdSampleatClient

{


class
Program

{


static
void Main(string[] args)

{


Service1Client proxy = new
Service1Client();

proxy.Open();


Console.WriteLine(“Session Id Fetched from the Service “ + proxy.GetSessionID());


string sessionid = proxy.InnerChannel.SessionId;


Console.WriteLine(“Session id Fetched at the Client = “+sessionid);


int res = sessionid.CompareTo(proxy.GetSessionID());


if(res==0)

{


Console.WriteLine(“Service Session Id and Clinet Session Id is Same “);

}

proxy.Close();


Console.ReadKey(true);

}

}

}

Output



 Conclusion 

This article explained about, Session ID in WCF. This article gave theoretical introduction and explanation of coding sample also.

Happy Coding

Single Instance Management in WCF

Objective

This article is part # 3 of Instance Management in WCF.

This article will explain about Singleton Service Instance mode. This article will give theoretical introduction and explanation of coding sample also. It will also discuss about various disadvantages of Singleton Service Instance mode and its potential place of uses.

Part # 1 of this series could be found Here.

Part # 2 of this series could be found Here. 

Singleton Service


  1. The Singleton Service Instance created only once.
  2. It created when the service host is created.
  3. It lives forever.
  4. It got disposed only when host shuts down.
  5. Singleton service instance does not require client to maintain any logical session.
  6. It does not required to use binding that supports transport level session.


Code

[ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]


public
class
Service1 : IService1,IService2 ,IDisposable

{

}

Explanation with example

Service Contract 1

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SingleServiceInstanceService

{

[ServiceContract(SessionMode=SessionMode.Required)]


public
interface
IService1

{

[OperationContract]


int GetDataFromRequiredContract();

}

}

 Service Contract 2

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SingleServiceInstanceService

{

[ServiceContract(SessionMode = SessionMode.NotAllowed)]


public
interface
IService2

{

[OperationContract]


int GetDataFromNotAllowedContract();

}

}

 Service

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SingleServiceInstanceService

{

[ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]


public
class
Service1 : IService1,IService2 ,IDisposable

{


int _Counter = 0;


public Service1()

{

}


public
int GetDataFromRequiredContract()

{

_Counter++;


return _Counter;

}


public
int GetDataFromNotAllowedContract()

{

_Counter++;


return _Counter;

}


public
void Dispose()

{

}

}

} 

  1. There are two contracts IService1 and IService2.
  2. For IService1 session mode is set to SessionMode=SessionMode.Required
  3. For IService2 session mode is set to SessionMode = SessionMode.NotAllowed
  4. Service is implanting both the contracts.
  5. Service Behavior is configured to single instance mode

ServiceBehavior(InstanceContextMode =InstanceContextMode.Single)]

 

Web.Config 

<system.serviceModel>

<services>

<service
name=SingleServiceInstanceService.Service1
behaviorConfiguration=SingleServiceInstanceService.Service1Behavior>

<!– Service Endpoints –>

<endpoint
address=RequiredService
binding=wsHttpBinding
contract=SingleServiceInstanceService.IService1>

</endpoint>

<endpoint
address=AllowedService
binding=wsHttpBinding
contract=SingleServiceInstanceService.IService2>

</endpoint>

<endpoint
address=mex
binding=mexHttpBinding
contract=IMetadataExchange/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior
name=SingleServiceInstanceService.Service1Behavior>

<serviceMetadata
httpGetEnabled=true/>

<serviceDebug
includeExceptionDetailInFaults=false/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

.

  1. In System.ServiceModel, we need to expose two addresses. One each for individual contracts.

Client

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Test.ServiceReference1;

namespace Test

{


class
Program

{


static
void Main(string[] args)

{


Service1Client proxy = new
Service1Client();


Console.WriteLine(proxy.GetDataFromRequiredContract().ToString());


Service2Client proxy2 = new
Service2Client();


Console.WriteLine(proxy2.GetDataFromNotAllowedContract().ToString());


Console.ReadKey(true);

}

}

}

Output

 

 

Explanation of output 

Since service instance is configured for Singleton, all the proxy will share the same service instance. That is why all proxy is incrementing the same value. And as the output, each time client is getting incremented value

Disadvantage 

  1. Having scalability problem.
  2. All requests to service will run on different worker thread, so it will cause synchronization problem.
  3. Only one client could have access to singleton service instance at a time. It will decrease throughput of the service.
  4. Responsiveness is very low
  5. Singleton Service instance should only be used, when no other options are available. For instance Global Log Book, Single Communication Port etc.

Conclusion 

This article explained about, Singleton Service Instance mode. This article gave theoretical introduction and explanation of coding sample also. It also discussed about various disadvantages of Singleton Service Instance mode and its potential place of uses.

Happy Coding