-1

I'm new to WCF and I wrote a sample WCF service which uses the InstanceContextMode. When I'm using the PerSession, my counter value doesn't gets incremented. Why doesn't it uses the same instance for every service call. Below is my code

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : IService1
{
    int count;
    public int Add(int a, int b)
    {
        count++;
        return a + b;
    }

    public int GetCount()
    {
        return count;
    }
}

WebConfig

<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

Client.cs

DemoWCFService.Service1Client client = new DemoWCFService.Service1Client();
        Console.WriteLine(""+ client.Add(10,20));
        Console.WriteLine("" + client.Add(10, 20));
        Console.WriteLine("" + client.Add(10, 20));

        Console.WriteLine("" + client.GetCount());
        Console.ReadKey();

Please help me with this.

  • Which type of session are you using from https://learn.microsoft.com/en-us/dotnet/framework/wcf/using-sessions#system-provided-session-types ? – mjwills Dec 09 '18 at 12:05
  • Possible duplicate of [Contract requires Session, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it](https://stackoverflow.com/questions/4406972/contract-requires-session-but-binding-basichttpbinding-doesnt-support-it-or) – mjwills Dec 09 '18 at 12:06
  • Possible duplicate of [WCF InstanceContextMode.PerSession](https://stackoverflow.com/questions/10338711/wcf-instancecontextmode-persession) – Ruslan F. Dec 09 '18 at 12:08

1 Answers1

0

BasicHttpBinding doesn't support PerSession. You had better use binding that supports session such as WSHttpBinding, WS2007HttpBinding.

To ensure you are using binding that supports session, you could use a service behavior

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

If your binding doesn't support session, it will cause error.

Ackelry Xu
  • 756
  • 3
  • 6