How do I select the correct instance mode during WCF development )?

Source: Internet
Author: User
When using the WCF instance model, have you considered these issues:
  • "How can I apply the instance mode in WCF correctly "?
  • "Can I follow the principles of using the instance mode in WCF "?

As we all know, when a client calls a service, it will eventually call an instance of the server. In the WCF Service, you can set the service instance through ServiceBehavior's InstanceContextMode.

InstanceContextMode is defined as follows:

// Summary:
// Specify the number of service instances that can be used to process calls contained in incoming messages.
Public enum InstanceContextMode
{
// Summary:
// Create a new System. ServiceModel. InstanceContext object for each session.
PerSession = 0,
//
// Summary:
// The new System. ServiceModel. InstanceContext object is created before each call and recycled after the call. If no session is created for the channel, the behavior of this value is as follows:
// System. ServiceModel. InstanceContextMode. PerCall is the same.
PerCall = 1,
//
// Summary:
// Only one System. ServiceModel. InstanceContext object is used for all incoming calls and will not be recycled after the call. If the service object does not exist, create one.
Single = 2 ,}

Since InstanceContextMode has three enumerated values, it indicates that the instances on the WCF server have three forms. In the normal development process, what principles should we follow to adopt the instance mode .?

First, let's take a look at the performance of server instances in three instance modes.

Service implementation: In the constructor of a service, initialize the counter and accumulate the counter for output during service calling. As follows:

Private int _ counter;
Public AddService ()
{
_ Counter = 0;
Console. WriteLine ("Single Mode ");
}

Public int Add (int x, int y)
{
Console. WriteLine ("Start invoke ...");
Console. WriteLine ("Invoke Thread Id is {0}", System. Threading. Thread. CurrentThread. ManagedThreadId );
_ Counter ++;
Console. WriteLine ("counter is: {0}", _ counter );
Return x + y;
}

 

1. Performance of various instance Modes 

PerCall Mode

When the client is called, the server output is as follows:

 

It can be seen that in PerCall mode, the instance is initialized every time a service call is made, and the instance Destruction is completed in the same thread as the service call.

PerSession Mode 

When the client is called, the server output is as follows:

 

It can be seen that in PerSession mode, the instance is initialized every time a service is called, but for each proxy, the Service uses the same instance object to serve the client. Note: The client value is the same proxy object (transparent proxy), not the computer

The session mode has three requirements: 1. Bind sessions supported; 2. The contract is a session contract; 3. The instance mode is PerSession.

Single Mode

When the client is called, the server output is as follows:

In Single mode, all clients share the same service instance object.
 

 2. How to Select a service instance Model

To select a service instance model, first check the advantages and disadvantages of the three models:

PerCall: 

Advantage: for a client call, the Service does not need to synchronize the status of the service call every time, because every call to the service requires the service to re-allocate resources; it can respond to concurrent calls from the client. The server creates and maintains multiple service instances in the memory only when concurrent calls are performed. During service calling, the client only holds the Service proxy and does not occupy the actual resources. Resources are obtained only when a service call occurs.

Disadvantage: You need to perform thread synchronization on your own for Parallel calls. Because each call needs to re-establish the resource status, it has a certain impact on performance.

In PerCall mode, the connection to the client is not released even if the service instance is constantly created and destroyed. Because establishing a connection requires more resources than creating or destroying a service instance.

 

PerSession:

 

Advantage: the server can identify different client proxies and allocate the same instance to the same client. The instance objects will remain until the session ends.

Disadvantage: the server resources are occupied during the entire session, so too many clients are not supported, because the cost of creating a service instance is relatively high; there is a scalability problem like the client and server modes.

Maintain the session between the server and the client. WCF simulates the session at the transport layer by means of the transport layer session or ws * binding.

 

 

Single:

Advantage: there is no need to consider the thread synchronization problem. The client calls the service in queue. The service can only be processed by one client at a time, and then serve the next client after processing is complete.

Disadvantage: the efficiency is relatively low because it is a serial service for the client. The scalability of the service is limited.

 

3. Design Services 

3.1. PerCall Mode

Design of a monotonic service (in the PerCall mode): Although it can be applied to any service, some problems should be noted during the design of such services: because the client does not need to care about the server instance model, in PerCall mode, the service also allocates new instance objects for client calls each time. After the call is completed, the instance is destroyed. Therefore, the client needs to perform status management. Therefore, when the client performs a service call, the server instance object needs to obtain the status from the storage media when instantiating it. Therefore, each operation pair should have only one parameter. During service call, initialize the status through parameters.

Example:

 

[ServiceBehavior (InstanceContextMode = InstanceContextMode. PerCall)]

Publicclass OrderService: IOrder, IDisposable

{
Private int _ counter;

Public OrderService ()
{
_ Counter = 0;
Console. WriteLine ("perCall Mode ");
Console. WriteLine ("counter is {0}", _ counter );
}

# Region IOrder Members

Public void Order (string orderId)
{
Int amount = GetStore (orderId );
UpdateStore (amount-order. Number );
}

# Endregion

Private int GetStore (string orderId)
{
String connectionString = ConfigurationManager. etettings ["connectionString"];
Using (var connection = new SqlConnection (connectionString ))
{
Connection. Open ();
// Obtain inventory quantity information
Return int;
}
}

Private void UpdateStore (int p)
{
String connectionString = ConfigurationManager. etettings ["connectionString"];
Using (var connection = new SqlConnection (connectionString ))
{
Connection. Open ();
// Update inventory information to the database
}
}

Public void Dispose ()
{
// Release resources
}
}

 

 3.2 PerSession Mode

When PreSession mode is used, it is best to use consistent configuration, even if WCF defines multiple contracts implemented by the Service as session or non-session mode in a service implementation, that is, all contracts support sessions to avoid defining services in different modes in one service implementation.

3.3 Single Mode 

The service in Single mode has a severe conflict with scalability. All client proxies of Single-mode services use the same service instance, and the WCF Service ensures service status synchronization. In the case of high concurrency access, it causes a serious reduction in performance. It is used only when the Singleton is applicable in application scenarios. In general, try to use other methods to synchronize the status, and try to avoid using the Single mode.

Postscript: a new understanding of the instance mode after reading "WCF Service programming.

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.