WCF 4 Step By Step Chapter 7 Note(Maintaining State and Sequencing Operations)

In the real world, a Web service might require that operations be invoked in a particular sequence.For example, if you are implementing shopping cart functionality
in a service, it does not make sense to allow a client application to perform a checkout operation to pay for goods before actually putting anything into the shopping cart.
You have at least two options to maintain state information between operations
-Maintain the shopping cart in the client application.
-used cookies stored on the user’s computer to store information
-but there was nothing to stop the client application directly modifying the data in the cookie or even inadvertently corrupting it in some manner
-Additionally, cookies can be a security risk
-Maintain the shopping cart contents in the service
-the service creates an instance of the shopping cart when an instance of the service is itself created by the host.each client gets their own instance of the service, with its own instance of the shoppingCart variable. By default, the first time each client invokes an operation in a service, the
host creates a new instance of the service just for that client
. How long does the instance last? The service instance isonly destroyed after the client has closed the connection to the host (in true .NET Framework fashion, you do not know exactly how long the instance will hang around after the client application closes the connection because it depends on when the .NET Framework garbage collector decides it is time to reclaim memory).

An instance of a WCF service that is created to handle requests from a specific client application and maintain state information between requests from that client application is called a Session.

You can control the relationship between client applications and instances of a service by using the InstanceContextMode property of the ServiceBehavior attribute of the service. You specify this attribute when defining the class that implements the service contract, as follows:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class ShoppingCartService : IShoppingCartService
{
...
}

The InstanceContextMode property can take one of the following three values: InstanceMode.PerSession, InstanceMode.PerCall, and InstanceMode.Single.

-The PerSession Instance Context Mode
                -The PerSessioninstance context mode specifies that the service instance is created when a client application first invokes an operation, andthe instance remains active, responding to client requests, until the client applicationcloses the connection.

                -It is possible fora client application to createmultiple threads and then attempt to invoke operations in the same session simultaneously.By default, a service is single-threaded and will not process more than one request at a time. If anew request arrives while the service is still processing an earlier request, the WCF runtimecauses the new request to wait for the earlier one to complete. The new request could possibly time-out while it is waiting to be handled.

You can modify this behavior; The ServiceBehaviorattribute has another property called ConcurrencyMode, you can set that property tospecify how to process concurrent requests in the same session, as shown in the following:

[ServiceBehavior(..., ConcurrencyMode =ConcurrencyMode.Single)]
public class ShoppingCartService : IShoppingCartService
{
...
}

ConcurrencyMode:ConcurrencyMode.Multiple,ConcurrencyMode.Single,ConcurrencyMode.Reentrant


-The PerCall Instance Context Mode
                - TheInstanceContextMode.PerCall instance context mode creates a new instance of the service every time the client application invokes anoperation. The instance is destroyed when the operation completes.
                -The advantage ofthis instance context mode is tha t it releases resources in the host between operations, greatly improvingscalability
                -The disadvantageof using this instance context mode is that maintaining state between operations  is more challenging. You cannot retain informationin instance variables in the service, soyou must save any required stateinformation in persistent storage such as a disk file or  database.

-The Single Instance Context Mode
                -TheInstanceContextMode.Single instance context mode creates a new instance of theservice the first time a client application invokes anoperation and then uses this same instance to handle all subsequent requests from this clientand every other client that connects to the same service. The instance is destroyed only when the host application shuts the service down.
                -The main advantage of this instance context mode, apart from the reduced resource requirements,  is thatall users can easily share data. Arguably,this is also the principal disadvantage of  this instance context mode.

Tip: The PerSession instance context mode is the default when you use an endpoint with  a configuration that requires sessions. This is actually most of the time, unless you disable  security (absolutely not recommended) or use theBasicHttpBinding binding, which does not  support sessions when the service host defaults tousing the PerCall instance context mode.

Maintaining State with the PerCall InstanceContext Mode (maintain state in a session-less service)

There are several ways you can achieve this,including generating an identifier  for the shopping cart when the service firstcreates it, returning this identifier to the client
application, and forcing the client to pass thisidentifier in to all subsequent operations as a  parameter. This technique, and its variations, arefrequently used, but suffer from many of the  same security drawbacks as cookies, as far as theservice is concerned; it is possible for a client  application to forge a shopping cart identifierand hijack another user’s shopping cart.

An alternative strategy is to employ the user’sown identity as a key for saving and retrieving state information.for example, thews2007HttpBinding bindinguses Windows Integrated Securityand transmits theuser’s credentials.

Note The same mechanism works even if you areusing a non-Windows specific mechanism to  identify users, such as certificates. Thus, it isa valuable technique in an Internet security environment.  The important thing is that you have a uniqueidentifier for the user—it does not have to be  a Windows user name.

==>One solution is use ws2007HttpBinding+passingdomain name + windows user name + passowrd and stor data to xml file(Serialization)

Selectively Controlling Service Instance Deactivation


With the WCF runtime, you can selectively controlwhen a service instance is deactivated, based on the operations being called.You can tageach method that implements an operation in a service with the OperationBehavior attribute.

[OperationBehavior(ReleaseInstanceMode =ReleaseInstanceMode.AfterCall)]
public bool Checkout()
{
...
}

The ReleaseInstanceMode property can take one of these values: 

ReleaseInstanceMode.AfterCallWhen the operation completes, the WCF runtime will release the service instance for recycling. If theclient invokes another operation, the
WCF runtime
will create a new service instance to handle the request.

ReleaseInstanceMode.BeforeCallIf a serviceinstance exists for the client application, the WCF runtime will release it for recycling andcreate a new one for handling the
client application request.

ReleaseInstanceMode.BeforeAndAfterCallThis isa combination of the previous two values; the WCF runtime creates a new serviceinstance for handling the operation and releases the service instance for recycling whenthe operation completes.
ReleaseInstanceMode.NoneThis is the defaultvalue. The service instance is managed according to the service instance context mode.

Sequencing Operations in a WCF Service

When using the PerSession instance context mode,it is often useful to be able to control the order in which a client application invokesoperations in a WCF service.

When you define an operation in a servicecontract, the OperationContract attribute provides two Boolean properties that you can use tocontrolthe order of operations and the consequent lifetime of the service instance:
IsInitiating If you set this property to true, aclient operation can invoke this operation to initiate a new session and create a new serviceinstance. If a session already exists,
this property has no further effect. By default,this property is set to true. If you set this property to false, then a client applicationcannot invoke this operation until another
operation has initiated the session and created aservice instance. At least one operation in a service contract must have this property setto true.
IsTerminating If you set this property to true,the WCF runtime will terminate the session and release the service instance when theoperation completes. The client application must create a new connection to the service beforeinvoking another operationwhich must have the IsInitiating property set totrue. The default value for this property is false.

The WCF runtime checks the values of theseproperties for consistency at runtime in conjunction with another property for the service contractcalled SessionMode.

SessionMode.Required The service will create asession to handle client requests if a session does not already exist for this client;otherwise, it will use the existing session for the client.

SessionMode.Allowed The service will create or usea session if the service binding supports them; otherwise, the service will notimplement sessions.

SessionMode.NotAllowed The service will not usesessions, even if the service binding supports them.

If you specify a value of false for theIsInitiating property of any operation, then you must set the SessionMode property of the service contractto SessionMode.Required. If you do not, the WCF runtime will throw an exception. Similarly,you can only set the IsTerminating property to true if the SessionMode property of the service isset to SessionMode.Required

Bindings and Sessions



Maintaining State by Using a Durable Service

A durable service is a WCF service that uses sessions to maintain state information.However, you can suspend or even halt a session,releasing the resources associated with the service instance while preserving the state of thesession. Later, you can start a new service instance, resume a session, and reload the state for thatsession into the service instance.

You indicate that a service is durable by taggingit with the DurableService attribute.A durable service requires a data store to persist the stateof its sessions.WCF and Workflow Foundation provide the SQL Persistence Provider for storingsession statein a SQL Server database. You can also build your own custom persistenceprovider if you wish to use some other mechanism.

As well as marking a service as durable, you also need to specify which operations can cause the service to save and resume session state. Youdo this with the DurableOperation attribute. This attribute provides similar functionality to the IsInitiating and IsTerminating properties of the OperationBehavior attribute; you can set a propertynamedCanCreateInstance to true to specify that the WCF runtime can create a new instance of a durable service when the operation is invoked. You can also set this property to false to indicate that the operation can only run by using an existing instance. Additionally,you can set the CompletesInstanceproperty to
true to indicate that the operation finishes the session, and any saved state held in the persistence store should be removed when the operation completes.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
[Serializable]
[DurableService]
public class ShoppingCartServiceImpl :IShoppingCartService
{
...
}

[DurableOperation(CanCreateInstance = true)]
public bool AddItemToCart(string productNumber)
{
...
}

[DurableOperation(CanCreateInstance = false)]
public bool RemoveItemFromCart(string productNumber)
{
...
}
...
[DurableOperation(CanCreateInstance = false)]
public string GetShoppingCartCart()
{
...
}


[DurableOperation(CanCreateInstance = false, CompletesInstance = true)]
public bool Checkout()
{
...
}

The SQL Persistence Provider requires that alldurable services are also serializable so  that their state can be saved to the persistencedatabase.

the instance ID generated by the durable serviceis passed in  the header of the SOAP messages that are exchangedby the client application and the  service. The protocol used by the service must populateand examine this information  automatically

Durable services are ideal for building systems that involve potentiallylong-running sessions that need to be able to survive service shutdown and restart.

Useful command

netsh http add urlacl url=http://+:8000/ user=UserName
netsh http show urlacl
netsh http delete urlacl url=http://+:8000/

In the Visual Studio Command Prompt window, runthe command:
svcutil ShoppingCartService.dll
c. Run the command:
svcutil/namespace:*,ShoppingCartClient.ShoppingCartServiceadventure-works.com.2010.06.04.wsdl *.xsd /out:ShoppingCartServiceProxy.cs


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值