Introduction
This article illustrates the use of the
InstanceContextMode
property used in the
ServiceBehaviour
attribute and how it can be so
handy in the latest communication technology Windows
Communication Foundation (WCF), introduced by
Microsoft as a part of the .NET framework SDK 3.0 and later
versions.
I will be creating a demo application which will make use
of the various instance context modes available in WCF,
along with the explanation.
Why WCF?
I thought of providing a little information about why
Windows Communication Foundation (WCF) is required in the
.NET framework when there are already communication
technologies like web services, enterprise services and
remoting. WCF is introduced by Microsoft to achieve a Single
Unified API for.NET services, so that in the future if any
one speaks about service communication in .NET it would be
only Windows Communication Foundation (WCF). Even though web
service has proved to be stable it has a lot of limitations
like statelessness and it also uses heavy soap to
communicate so it is relatively slow. If you take remoting
into consideration it can be consumed only by a .NET client
and it could either be stateless or can only afford a
singleton state.
When you consider WCF, it has a lot of flexibility which
would allow you to configure the WCF application as per your
needs. It can use many multiple message formats like text,
Soap, Binary, REST and MTOM and different bindings like
basicHttpBinding, wsHttpBinding, netTcpBinding
and dualHttpBindings
.
WCF can also maintain session based instances, singleton
and also be stateless. This is achieved using the
InstanceContextMode
property, which we will be
discussing in this article using a demo application.
Three Instance Context Modes
As I have mentioned ealiern,
InstanceContextMode
is nothing but a property
which is available in the System.ServiceModel
.
This library is the one which encloses almost all the
important WCF members. InstanceContextMode
property is mainly used in the ServiceBehaviour
attribute in order to mention what kind of state maintenance
your WCF application should provide. The
ServiceBehaviour
attribute is designed at
decorating the implementation classes in WCF.
There is also an enumerator available in the
Sytem.ServiceModel
library named as
InstanceContextMode
and it can be used in order
to set the property InstanceContextMode.
There are three instance context modes available. I’ve
listed them below:
PerCall
When you provide the instance context mode property as
PerCall, it is like instructing your implementation class
that state doesn’t have to be maintained, so all the calls
would become stateless. Below is the sample C# code showing
how the property has to be set.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
Since it is not going to maintain any states, you can use
thebasicHttpBinding
for your WCF
application.Single
When you provide the instance context mode property as
Single, it is like instructing your WCF implementation class
to maintain a singleton state. What I meant by saying
singleton would be clear for the readers who have exposure
to the singleton design pattern in C# programming. A
singleton class is a class for which at any point of time
only one instance can be created and the same instance will
be reused on subsequent requests.”Below is the sample C# code showing how the property has
to be set.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
Since it is going to maintain a single instance state,
you cannot use thebasicHttpBinding
, but you
can use any of the other bindings like
wsHttpBinding
.PerSession
When you provide the instance context mode property as
PerSession, it is like instructing your implementation class
state that it has to be maintained based on client sessions.
This is one major advantage of using WCF which offers
session based state maintenance which was never previously
offered by any of Microsoft’s communication technologies
like Remoting or Web Services.Below is the sample C# code showing how the property has
to be set.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
No surprise that this also doesn’t work with
basicHttpBinding
, but works with all the other
available bindings.
Now let us move onto creating the Demo Application. Let’s
create a sample Banking Application which will explain the
Instance Context Modes pretty noticeably.
Banking Service Demo Application
Create Blank Solution
In the demo application we would be creating all the
projects, including the client application in the same
solution. So as a first step let us create a blank solution
to which we will be adding all the projects to and name it
as InstanceContextModeDemoSolution
.
Create Contract Project
In WCF it should always be imbibed by the developers that
the contract part should always be created as a separate
project. This is because you have to provide the contract
library to the client application, since it will be making
use of it. If you mingle the contract and the implementation
stuff in the same project, then you will end up providing
the client with the implementation part as well.
Follow the below steps:
- Add a new project of type class library to the solution
and name it asBankingService.Contract
. - Delete the default
class1.cs
file. Add an
interface, name it asIBankingService
and make
it public - Add the reference to
System.ServiceModel
library from GAC.
Below is the interface code
using System;
using System.ServiceModel;namespace BankingService.Contract
{
[ServiceContract]
public interface IBankingService
{
[OperationContract]
void DepositFund(int accountId, double amount);
[OperationContract]
void WithdrawFund(int accountId, double amount);
[OperationContract]
double GetBalance();
}
}
The interface has three method declarations
DepositFund
, WithdrawFund
and
GetBalance
. These methods have to be
implemented in the implementation class.
Create Implementation Project
Now let us create the implementation project which would
contain the implementation classes for the contract which we
have defined in the contracts project.
Follow the below steps:
- Create a project of type class library and name it
BankingService.Implementation
. - Add the reference to the
BankingService.Contract
project and
System.ServiceModel
. - Rename the default class as
BankingService
. - Implement the interface
IBankingService
in
theBankingService
class. - Create a class called
Account
.
Below is the Account class code
namespace BankingLibrary
{
public class Account
{
public int AccountId { get; set; }
public string HolderName { get; set; }
public double Balance { get; set; }public Account()
{
Console.WriteLine(“Account Object Created”);
}public void Deposit(double amount)
{
Balance += amount;
}public void Withdraw(double amount)
{
Balance -= amount;
}public double GetBalance()
{
return Balance;
}
}
}
Below includes the code for the Implementation class
BankingService
, note that the
ServiceBehaviour
attribute is used and the
InstanceContextMode
property is set to
InstanceContextMode.PerCall
.
namespace BankingService.Implementation
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class BankingService : IBankingService
{
Account _account;public BankingService()
{
_account = new Account();
}#region IBankingService Members
public void DepositFund(int accountId, double amount)
{
_account.Deposit(amount);
}public void WithdrawFund(int accountId, double amount)
{
_account.Withdraw(amount);
}public double GetBalance()
{
return _account.GetBalance();
}#endregion
}
}
Create the Host Application
WCF applications always require a host application which
will host the WCF service, so that it is available for the
clients to consume. There are different ways of hosting the
service but here we will use IIS hosting using a .svc file.
Follow the steps:
- Create a Web Application, choose the Location as HTTP
instead of FileSystem. - Provide the virtual directory as http://localhost/BankingService.
- Add the reference to the Contract and Implementation
projects. - Delete the default.aspx page. Add a text file and rename
it to Service.svc - Open Service.svc file and add the below tag
<%@ ServiceHost Service="BankingService.Implementation.BankingService" %>
- Open the web.config file and add the below section under
the configuration tag. Make sure you are using
wsHttpBinding.
<system.serviceModel>
<services>
<service behaviorConfiguration=”BankingServiceBehaviour” name=”BankingService.Implementation.BankingService”>
<endpoint address=”” binding=”wsHttpBinding” contract=”BankingService.Contract.IBankingService”></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name=”BankingServiceBehaviour”>
<serviceMetadata httpGetEnabled=”True” httpGetUrl=””/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Build your application and now it is hosted on IIS, ready
for the clients to consume.