Single Instance Based - Instance Management in WCF hosted on Web App


Today, in this article lets dig out some theory stuff first and later we will try to implement the studied concepts i: e Per Single based Instance Management using WCF.

Based on My Earlier Articles

Per Call Based - Instance Management in WCF: http://www.c-sharpcorner.com/UploadFile/54db21/per-call-based-instance-management-in-wcf-hosted-on-web-ap/

Per Session Based - Instance Management in WCF: http://www.c-sharpcorner.com/UploadFile/54db21/per-session-based-instance-management-in-wcf-hosted-on-web/

Let's also try this good concept eventually.

In the meanwhile I will take very less time in letting you know the main key differences in tabular format. Which is described as below

 

S.No

 

 

Per-Call Based

 

Per Session- Based

 

Single Instance Based

 

 

1

 

New Service Instance will be created for every client request. In Simple terms "Single Client but Many Instances".

 

 

For Every Client New Service Instance will be created. It Simple terms "Dedicated Instance for Client" or "Each Client has allocated independent instance".

 

 

Here the entire clients are interacted in very rigid fashion as they will be communicating with single service instance.

In Simple terms "Many Clients but Single Instance".

 

 

 

 

2

 

Instance will be disposed or discharged only after the response is reverted back to client.  In Simple terms" Deliver the Content and die"

 

Instance will be disposed or discharged only after the response is reverted back to client. In Simple terms" Deliver the Content and die"

 

 

But, Here What happens exactly is the instance is disposed or deleted when the client is destroyed. I mean in Simple term "Service Instance will be there forever until and unless client is destroyed".

 

 

Question Arises: What is Instance Management?

We can say it is a type of rules governed to manage the services with clients. It provides high end in scalability, durability and effective transaction management.

Question Arises: What is Per-Single Based Instance Management?

Key Point Here To Remember

  • Basically we can term it as "SHARED SERVICE" because scenario behind this all the clients calls are divergently connected to single instance and itself says half of the hints like its singleton. I mean to say in simple terms "Single Instance is generated only once and lives lifelong and longer. It is generated when the host is created." 

  • The Client does not needs sessions because singleton instance will generate a session ID for the client. 

  • The main reason to go and opt for singleton instance management is you can provide valuable and effective stateful interaction across multiple clients deployed

Let's Now Try and Dig for Some Disadvantages or Demerits as well

  • When the request calls are more from the client the singleton instance which will be assisting towards request will be served with multiple threads. But though provide response simultaneously at some point of peek time the concurrency will be lost and throughput is genuinely lower with less availability to the client

  • Avoiding it would be much better unless you have got multiple clients who want to have shared stateful resource.

So, let's try to implement this concept so that we can get much better idea on this:

So, firstly we will create simple method in IService1, Where the Complete Code of IService1.cs looks like this:

using System;
using System.ServiceModel;
namespace SimpleInstanceManagement
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class Service1 : IService1, IDisposable
    {
        public int Heighter = 0; public int SimpleMethod(int a)
        {
            a = (Heighter = Heighter + 1); return a;
        }
        public void Dispose()
        {
            Heighter = Heighter - 1;
        }
    }
}


The Complete Code of Service1.svc looks like this:

using System.ServiceModel;

namespace SimpleInstanceManagement
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        int SimpleMethod(int a);
    }
}

The Complete Code of Web.Config looks like this: 
 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Application">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SimpleInstanceManagement.Service1" behaviorConfiguration="Application">
        <endpoint address="/SimpleAddress" binding="wsHttpBinding" contract="SimpleInstanceManagement.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:49257/Service1.svc"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>
  

I have created New Web Application where I have added it to existing solution files. I have specified service reference with a link as given below:


http://localhost:49257/Service1.svc

The Complete Code of WebForm1.aspx looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Instance.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title
>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <center>
            <table>
                <tr>
                    <td>
                        <asp:Label ID="Label1" runat="server" Text="Please Enter Some Value" ForeColor="Brown"
                            Font-Bold=" true" Font-Italic="true"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="Click Here" OnClick="Button1Click"
                            Style="margin-left: 0px" Width="118px" />
                    </td>
                </tr>
            </table>
        </center>
    </div>
    </form
>
</body>
</
html>

The Complete Code of WebForm1.aspx.cs looks like this:

using System;
using Instance.ServiceReference1;

namespace Instance
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void PageLoad(object sender, EventArgs e)
        {

        }

        protected void Button1Click(object sender, EventArgs e)
        {
            if (TextBox1.Text != null)
                if ((TextBox1.Text) == "1")
                {
                    var ab = new Service1Client();
                    Response.Write("<center>The Value is: <b>" + ab.SimpleMethod((Convert.ToInt32(TextBox1.Text))) +
                    "</br></b></center>");
                    Response.Write("<center>The Value is: <b>" + ab.SimpleMethod((Convert.ToInt32(TextBox1.Text))) +
                    "</br></b></center>");
                    Response.Write("<center>The Value is: <b>" + ab.SimpleMethod((Convert.ToInt32(TextBox1.Text))) +
                    "</br></b></center>");

                    Response.Write("<center><i>Second Instance Created for Service</i></center>");
                    var bc = new Service1Client();
                    Response.Write("<center>The Value is: <b>" + bc.SimpleMethod(Convert.ToInt32(TextBox1.Text)) +
                    "</br></b></center>");
                    Response.Write("<center>The Value is: <b>" + bc.SimpleMethod(Convert.ToInt32(TextBox1.Text)) +
                    "</br></b></center>");
                    Response.Write("<center>The Value is: <b>" + bc.SimpleMethod((Convert.ToInt32(TextBox1.Text))) +
                    "</br></b></center>");
                    Response.Write("<center>The Value is: <b>" + bc.SimpleMethod((Convert.ToInt32(TextBox1.Text))) +
                    "</br></b></center>");
                }
                else
                {
                    Response.Write("<center><b><i>Please Enter Some Values or Enter Correct Values</i></b></center>");
                }
        }
    }
}


The Output of the application looks like this:

Per Single Output.png

The Output of the application if entered wrong or null:


Per Single Output Error.png
I hope this article is useful for you. 


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.