WCF learning-WCF Service instance mode

Source: Internet
Author: User
Tags exit in

The purpose of learning WCF is to use WCF to establish a service so that the sivlerlight program can query and modify the content of Oracle Data. Database Operations must inevitably involve database transactions ), database transaction-based operations require that the transaction object remain unchanged after the transaction starts for a specific client program, so as to ensure the success of the commit or rollback operations, after querying the relevant information, it seems that you can control it through the service instance of WCF.

I. Basic Introduction

After trying to create a basic WCF instance, I began to learn about the WCF Service instance. The service instance mainly controls the server behavior when the WCF client interacts with the server. There are three instance modes:


1: monotonous Service (Per-call service): each client request is allocated with a new service instance.


2: Session Service: allocates a service instance for each client connection.

3: Singleton service: all clients share the same service instance for all connected and activated objects. Similar to the singleton mode of net remoting

Ii. Sample Code

An example is provided to illustrate the differences between several services:

1. Contract)

There are three functions: setvalue, getvalue, and getsid.

[ServiceContract]    public interface IService1    {        [OperationContract]        string SetValue(int value);        [OperationContract]        string GetSid();        [OperationContract]        string GetValue();        // TODO: Add your service operations here    }

Servicebehavior)

(1): constructor: print the sessionid of the current connection

(2): setvalue function: assign values to intvalue variables in the class

(3): getvalue function: obtains the value of the intvalue variable in the class.

(4): getsid function: obtains the sessionid of the current connection.

(5): The dispose function displays the disconnected information and sessionid of the connection.

public class Service1 : IService1,IDisposable    {        private int intvalue;        private string currentsid;        public Service1()        {            try            {                currentsid = OperationContext.Current.SessionId;            }            catch (Exception ex)            {                Console.WriteLine("get current sid failed,operatincontext.currect is null?" +(OperationContext.Current == null) +"  ");            }                        Console.WriteLine("Service1 connected:" + currentsid);        }        public string SetValue(int value)        {            intvalue = value;            return string.Format("You entered: {0}", value);        }        public string GetSid()        {            return currentsid;        }        public string GetValue()        {            return intvalue.ToString();        }        #region IDisposable Members        public void Dispose()        {                         Console.WriteLine("Service1 disconnected:" + currentsid);               }        #endregion    }


2. HOST ):

ServiceReference1.Service1Client sc1 = new ServiceReference1.Service1Client();            string a;            int tmpInt;            while ((a = Console.ReadLine()) != "exit")            {                if (int.TryParse(a,out tmpInt))                    Console.WriteLine(sc1.SetValue(tmpInt));                else if (a == "get")                    Console.WriteLine(sc1.GetValue());                else if (a == "sid")                    Console.WriteLine(sc1.GetSid());            }            ((IDisposable)sc1).Dispose();

App. config corresponding to the Host:

  <?xml version="1.0" encoding="utf-8" ?> - <configuration>- <system.serviceModel>  <diagnostics performanceCounters="All" /> - <behaviors>- <serviceBehaviors>- <behavior name="NewBehavior0">  <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8585/is/metadata" />   </behavior>  </serviceBehaviors>  </behaviors>- <services>- <service behaviorConfiguration="NewBehavior0" name="WcfService1.Service1">  <endpoint address="" binding="wsDualHttpBinding" bindingConfiguration="" name="ep1" contract="WcfService1.IService1" /> - 

Used hereWsdualhttpbindingBecause not all bindings support session, binding has little impact on per-call and Singleton. For persession, you must use a specific binding. Otherwise, the end point is percall, and the specific query can be performed again.


3. Client)

Function:

When you enter a number in the command line, call the setvalue function, assign the number to the intvalue of WCF, and print the prompt,

When you enter get in the command line, call the getvalue function to obtain and print the intvalue.

When you enter the SID in the command line, call the getsid function to obtain the current sessionid and print it out.

When you enter exit in the command line, disconnect and exit the function.

 ServiceReference1.Service1Client sc1 = new ServiceReference1.Service1Client();            string a;            int tmpInt;            while ((a = Console.ReadLine()) != "exit")            {                if (int.TryParse(a,out tmpInt))                    Console.WriteLine(sc1.SetValue(tmpInt));                else if (a == "get")                    Console.WriteLine(sc1.GetValue());                else if (a == "sid")                    Console.WriteLine(sc1.GetSid());            }            ((IDisposable)sc1).Dispose();

3. Test the three instance Modes

1: persession Mode

By default, WCF runs in this mode without modifying the code.

When multiple client command lines are opened, the host command line prints a sessionid.

In each client command line, the setvalue, getvalue, and getsid operations are consistent within the session and are not related to other sessions, as follows:

2: percall Mode

You need to add a statement before the class declaration of service1. The statement is as follows:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]    public class Service1 : IService1,IDisposable

In this mode, a new session will be opened for each operation, but the sessionid is the same. The session will be closed immediately after the operation is completed, and the intvalue value will not be saved, if you open multiple clients, the sessoinid is the same, as shown below:


3. Single Mode

You need to add a statement before the class declaration of service1. The statement is as follows:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]    public class Service1 : IService1,IDisposable

In this mode, no matter how many clients are opened, the server has only one session, and the intvalue of multiple clients is shared (that is, clienta sets this value to 123, the value obtained by clientb is 123)

In this mode, there is no sessionid concept. When you try to obtain this ID, a null value is returned, as shown below:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.