Programming WCF services translation notes (7)

Source: Internet
Author: User

Chapter 4 introduces the related technologies of instance management. "WCF supports three types of instance activation: the monotonous service allocates (destroys) a new service instance for each client request. Session Service allocates a service instance for each client connection. The last is Singleton service. All clients share the same service instance for all connections and activation objects ."

For the translation of per-call service, I hesitated for a long time and finally decided to translate it into a monotonous service based on the translation of Singleton service, that is, to create a service instance for each call, corresponds to the singleton service. Is it appropriate? In fact, the best translation is to keep the original text unchanged, but for the whole book, there are a lot of inconveniences if you keep the English term.

The configuration of instance mode is completed through servicebehavior. The following is the definition of servicebehaviorattribute:
Public Enum instancecontextmode
{
Percall,
Persession,
Single
}
[Attributeusage (attributetargets. Class)]
Public sealed class servicebehaviorattribute: attribute ,...
{
Public instancecontextmode
{Get; set ;}
// More Members
}

Per-call service)

Monotonous service:
 
Perform the following steps:
1. The client calls the proxy, which forwards the call to the service.
2. Create a service instance in WCF and then call the method of the service instance.
3. When a method call returns, if the object implements the idisposable interface, WCF calls the idisposable. Dispose () method.
4. The client calls the proxy, which forwards the call to the service.
5. Create an object in WCF and call the object method.

One of the most important advantages of monotonous services is its ability to save resources and support system scalability. Because the life cycle of a service instance only exists during one call, this method can effectively improve system performance, especially for service instances that hold expensive resources. In addition, when a service instance is destroyed, WCF will not disconnect from the client (through the client proxy), which consumes much less resources than creating an instance and connection.

The advantages of the monotonous service are more obvious in transaction programming and queue service. It can ensure the synchronization of the instance state in transaction programming. For the disconnection call of the queue, then the monotonous service can establish a simple ing between the service instance and the message in the discrete queue.

The configuration of the monotonous service is as follows:
[Servicecontract]
Interface imycontract
{...}

[Servicebehavior (instancecontextmode = instancecontextmode. percall)]
Class myservice: imycontract
{...}
Note that the servicebehavior feature can only be applied to the class, as shown in the definition of the feature described above. In fact, this is also a reasonable constraint, because if you apply servicebehavior to an interface, because the interface cannot be instantiated, errors will naturally occur.

Monotonous service instances are state-related. However, because the instances are created at the beginning of the call and are destroyed after the call, such monotonous service instances cannot be saved. To solve this problem, we can introduce the database or file storage status, or use the temporary storage status of global variables. In order to obtain the status, the potential meaning is that each operation of the monotonous service should define a parameter to pass the status or status ID.

One sentence in the book is very important: "If the monotonous service is not related to the status, there is no need for the monotonous activation mode. To be precise, it is precisely because of the State, especially the expensive state that we need to use the monotonous mode ." Many times, we think that the life cycle of a monotonous service instance exists in each call. Therefore, we take it for granted that such a service instance should be stateless. This operation may simply execute a task, rather than performing operations on the properties of the service object. This seems to be true on the surface, but here we ignore the root cause of our monotonous service, because the essence of the monotonous activation mode is that it can release the expensive resources held by instances in a timely manner, resources here are generally in a state. If you do not need to maintain the status, you think there is not much loss in performance, so we do not need to adopt the monotonous activation mode. After all, instances are frequently created and destroyed, it will still have a certain impact on performance.

For a WCF Service, the monotonous service is the best instance activation mode. The book introduces: "a powerful argument is that monotonous services are more conducive to system scalability. To better support scalability, the prime rule of service design is 10x, that is, each service designed should be able to handle at least one load level or more. This is an engineering principle. When designing a system, engineers will never be able to "zoom in" and only consider the processing of the current specified load. If a building can only support the bearing capacity determined by the current demand, will someone dare to live? If an elevator can only bear the weight of the specified six passengers, will anyone take the ride? The same is true for software systems. Why can't we design a system for the current specified load? Assuming that this design approach is adopted, once each user of the system increases the business volume, the system will become vulnerable. A well-designed system must be able to survive the test of time. To achieve this goal, we need to apply the golden Law of 10 X to effectively utilize the scalability provided by monotonous services. Another strong argument for adopting monotonous services is about transaction processing. As described in Chapter 7th, transactions are absolutely necessary for every system. monotonous services are conducive to implementing the transaction programming model without considering the system load ."

Session Service

From the execution and activation modes, the session service is equivalent to the client activation mode in. Net remoting. That is, create a dedicated service instance for each client. The instance will not be destroyed as long as the session has not ended.

"A client session is a service endpoint corresponding to a proxy. If the client creates another proxy for the same or different endpoints, the new proxy will be associated with the new instance and session ." According to this sentence, we can understand that for session service, a client proxy corresponds to a service instance. In other words, the services in the session service correspond to the proxy, rather than a client. This is different from the client activation mode of. Net remoting.

In addition, the session service has scalability problems. Because each client needs to maintain a session, it is too costly to create a dedicated service instance if multiple independent clients exist.

The way to configure the session service is still to use the servicebehavior feature, as shown below:
[Servicebehavior (instancecontextmode = instancecontextmode. persession)]
Class myservice: imycontract
{...}

However, the default value of instancecontextmode is instancecontextmode. persession. If instancecontextmode is not set, the service is a session service by default.

It is not enough to configure instancecontextmode for the service, because the session service must require the client to maintain a session, which requires that the client's WCF runtime know whether the service uses a session. Therefore, we need to set the service contract through the sessionmode attribute provided by servicecontract. Sessionmode is defined as follows:
Public Enum sessionmode
{
Allowed,
Required,
Notallowed
}

"The default value of sessionmode is sessionmode. allowed. When the client imports the contract metadata, the Service metadata will contain the sessionmode value and reflect the content in the field ."

If the sessionmode of the service is configured as sessionmode. allowed, it does not necessarily mean that the service is a session service. The following describes various situations:
1. if the service is configured as a monotonous service, the service has nothing to do with sessionmode;
2. if the service is configured as a session service and the sessionmode is allowed, then:
(1) If the service is bound to basichttpbinding, the service is a monotonous service;
(2) If the service is bound to a wshttpbinding that does not contain secure and reliable message transmission, the service is a monotonous service;
(3) If the wshttpbinding binding used by the Service includes secure (default configuration) or reliable message transmission, or use nettcpbinding and netnamedpipebinding to bind the service, the service serves sessions.

When the sessionmode is required, the service cannot use basichttpbinding binding or wshttpbinding binding that does not contain secure and reliable message transmission. This is verified when the service is loaded. The author suggests, "to design a session contract, I suggest using sessionmode. required instead of the default sessionmode. allowed ."

If sessionmode is notallowed, it always adopts the monotonous service mode regardless of service configuration. However, if the contract uses nettcpbinding or netnamedpipebinding binding, the sessionmode of the service cannot be set to notallowed. The author suggested that "services are always configured as monotonous services when sessionmode. notallowed is selected ".

Avoid mixed definitions of monotonous services and session contracts in the same session service type, even if WCF allows such Configuration:
[Servicecontract (sessionmode = sessionmode. Required)]
Interface imycontract
{...}

[Servicecontract (sessionmode = sessionmode. notallowed)]
Interface imyothercontract
{...}

// Avoid
Class myservice: imycontract, imyothercontract
{...}

A session must be reliable. A service that implements a session contract should use the binding that supports reliable transmission sessions for all the contracts published by the endpoints it contains.

"In general, once the client closes the proxy, the session ends. However, the client can also forcibly terminate the session or terminate the session due to a communication failure. Each session also contains an idle timeout value. The default value is 10 minutes. If the client does not perform any operations within 10 minutes, the session will be automatically terminated even if the client expects to continue using the session. If the session is terminated because of idle timeout, A communicationobjectfaultedexception exception is returned when the client tries to use its proxy. You can configure different timeout values for the client and service by configuring different values in binding. Reliable Transport-layer session binding provides the reliablesession attribute, type: reliablesession or optionalreliablesession. The reliablesession class defines the inactivitytimeout attribute, which belongs to the timespan type. It can be used to configure a new idle timeout value ."

Note that the default value of the inactivitytimeout attribute is 10 minutes. You cannot set this value to a value smaller than or equal to 0. Otherwise, an argumentoutofrangeexception is thrown.

For exampleCodeUse programming to set the idle timeout value of TCP binding to 25 minutes:

Nettcpbinding tcpsessionbinding = new nettcpbinding ();
Tcpsessionbinding. reliablesession. Enabled = true;
Tcpsessionbinding. reliablesession. inactivitytimeout = timespan. fromminutes (25 );

This is equivalent to the config file:

<Nettcpbinding>
<Binding name = "tcpsession">
<Reliablesession enabled = "true" inactivitytimeout = "00:25:00"/>
</Binding>
</Nettcpbinding>

If the timeout value is configured for both the client and the service, the short timeout value prevails.

Singleton Service

If we are familiar with the design model, we can think about the singleton service in singleton mode. The Singleton service only has one service instance for all clients. "The lifetime of the singleton service is unlimited. It is released only when the host is disabled. When a host is created, the singleton service is created and can only be created once ."

You can use the instancecontextmode. Single instancecontextmode attribute to configure the singleton service:
[Servicebehavior (instancecontextmode = instancecontextmode. Single)]
Class mysingleton :...
{...}

As long as it is a singleton service, even if the Service supports multiple contracts, some of these contracts need sessions, and some do not need sessions, the call at different endpoints is still passed through the same instance. Even if the proxy is disabled, the singleton service is not terminated.

Some initialization work may be required when instantiating a singleton service object. If you use the default constructor and host the service through servicehost, there is no way to do this. Of course, we can also implement the initialization work in the default constructor. However, if the initialization work requires some special customization steps, especially when the operation status or parameters need to be passed in, the default constructor is too stretched.

WCF provides another way to initialize the singleton service, that is, using the special constructor provided by the servicehost class, you can receive an object:
Public class servicehost: servicehostbase ,...
{
Public servicehost (Object singletoninstance,
Params URI [] baseaddresses );
Public Virtual Object singletoninstance
{Get ;}
// More Members
}

note that singletoninstance In the constructor must be a single-instance service object. Therefore, the initialization and hosting of the singleton service can be implemented as follows:
// Service Code
[servicecontract]
interface imycontract
{< br> [operationcontract]
void mymethod ();
}< br> [servicebehavior (instancecontextmode = instancecontextmode. single)]
class mysingleton: imycontract
{< br> int m_counter = 0;

Public int counter
{
Get
{
Return m_counter;
}
Set
{
M_counter = value;
}
}
Public void mymethod ()
{
M_counter ++;
Trace. writeline ("counter =" + counter );
}
}
// Host code
Mysingleton Singleton = new mysingleton ();
Singleton. Counter = 42;

Servicehost host = new servicehost (Singleton );
Host. open ();
// Do some blocking callthen
Host. Close ();

// Client code
Mycontractclient proxy = new mycontractclient ();
Proxy. mymethod ();
Proxy. Close ();

// Output:
Counter = 43

Obviously, this constructor provided by servicehost has room for improvement, that is, the object type parameters obviously do not have type security. Therefore, the author of this book defines the new servicehost class and introduces the generic type:
Public class servicehost <t>: servicehost
{
Public servicehost (T Singleton, Params URI [] baseaddresses)
: Base (Singleton, baseaddresses)
{}
Public Virtual t Singleton
{
Get
{
If (singletoninstance = NULL)
{
Return default (t );
}
Return (t) singletoninstance;
}
}
// More Members
}

The relationship between the singleton service and scalability can be described as "difficult to deal ". Therefore, unless in special circumstances, avoid using the singleton service whenever possible.

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.