Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 13: Remoting and XML Web Services

7

 

 

 

Activation and Proxies

Topic Objective

To show how the remoting framework supports serverside and client-side activation of remote objects and to describe the differences between serverside and client-side activation.

Lead-in

The remoting framework supports server-side and client-side activation of remote objects.

!Before Using a Remote Object, the Client Must Activate It

#By calling new, Activator.CreateInstance, or Activator.GetObject

!Activation Returns Proxy Used by Client to Access Remote Object

#Proxy represents remote object in client’s AppDomain

#Proxy forwards client’s calls, and returns results and exceptions

!Server-Side Activation – Automatic Instantiation by Server

#Single call object handles only one request (stateless)

#Singleton object services multiple clients and requests (stateful)

!Client-Side Activation – Instantiation by Explicit Client Call

#State maintained between method calls for specific client instance

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The remoting framework supports server-side and client-side activation of remote objects.

Server-side activation means that when a client attempts to access the object, the object is instantiated on the server automatically. Client-side activation, on the other hand, means that the object is instantiated in response to a deliberate activation request from a client.

You can select the best activation model to control the instantiation and lifetime of a remote object.

Methods of Remote Object Activation

Before a client can use a remote object, the remote object must be activated, and the client must obtain a proxy to access the remote object.

You can activate a remote object by calling new or by calling the following methods of the Activator class:

!Activator.CreateInstance

Used to create an object instance

!Activator.GetObject

Generally used to connect to an object that is already running at a specified Uniform Resource Identifier

8Module 13: Remoting and XML Web Services

The Role of Proxies in Remote Object Interaction

When a client activates a remote object, the client obtains a proxy to the class instance on the server. Any interaction with a remote object occurs by reference through the proxy. The proxy object acts as a representative of the remote object and ensures that all calls that are made on the proxy are forwarded to the correct remote object instance. All methods that are called on the proxy are automatically forwarded to the remote class, and any results are returned to the client.

From the client’s perspective, this process is identical to the process of making a local call. Any exceptions that are thrown by the remote object are automatically returned to the client. Because those exceptions are returned to the client, the client can use try/catch blocks around sections of code to trap and handle exceptions.

Server-Side Activation

Server-side activation supports single call and singleton modes of activation.

Single Call Objects

A single call object services only one request. Single call objects are useful in scenarios in which:

!The overhead of creating an object is not significant.

!Objects are configured in a load-balanced fashion.

!State information is usually not needed between calls.

Because single call objects cannot hold state information between method calls, they are sometimes referred to as stateless objects.

Singleton Objects

A singleton object services multiple clients and multiple requests. Therefore, a singleton object can store state information between client invocations. Singleton objects are useful when you want to share data explicitly between clients and method invocations, and when the overhead of creating and maintaining objects is substantial.

Because singleton objects can maintain their state over a prolonged period of time, they are sometimes referred to as stateful objects.

Module 13: Remoting and XML Web Services

9

 

 

 

Client-Side Activation

Client-activated objects are activated on a request from the client. This method of activating server objects is similar to the classic COM coclass activation. The activation process is as follows:

1.When the client requests a server object, an activation request message is sent to the remote application.

2.The server then creates an instance of the requested class and returns an ObjRef object to the client application that invoked it.

3.A proxy is then created on the client side by using the ObjRef object.

A client-activated object can store state information between method calls for its specific client. However, state information is not shared between multiple client-activated objects. Each request for a remote object instance returns a proxy to an independent instance of the server type.

A useful function of client-activated objects is that constructor arguments can be passed by the local application to the constructor of the object in the remote application.

10

Module 13: Remoting and XML Web Services

Lease-Based Lifetime

Topic Objective

To explain how using a leasing mechanism can extend the lifetime of clientactivated remote objects.

Lead-in

You can control the lifetime of client-activated remote objects by using a leasing mechanism.

!A Leasing Mechanism Controls the Lifetime of a ClientActivated Remote Object

!An Object’s Lease Time Can Be Extended

!When an Object’s Lease Time Reaches Zero

#The object is disconnected from remoting infrastructure

#The object may be garbage-collected

#A lease provides an alternative to reference counting

*****************************ILLEGAL FOR NON-TRAINER USE******************************

You can control the lifetime of client-activated remote objects by using a leasing mechanism. When an object is first created, it is given a lease time. When the lease time of the object reaches zero, the object is disconnected from the remoting infrastructure. After the references to the object from within the object’s application domain have been freed, the object may be collected when the next garbage collection occurs.

You can extend the lease on an object by using a number of mechanisms. For more information about extending the lease on an object, see “Lease-Based Lifetime Concepts” in the .NET Framework Software Development Kit (SDK) documentation.

You can use leases to manage the lifetime of remote objects as an alternative to reference counting, which tends to be complex and inefficient over unreliable network connections.

A potential disadvantage of leasing is that the lifetime of a remote object may be extended for longer than is required. However, the advantages of reducing network traffic that is devoted to reference counting and the pinging of clients outweigh the disadvantage of the extended lifetimes of remote objects.

Module 13: Remoting and XML Web Services

11

 

 

 

Object Marshaling

Topic Objective

To explain how objects are marshaled in .NET Remoting.

Lead-in

Because calls to a remote object can cause other objects to be passed across a remoting boundary, you should understand how objects are marshaled in

.NET Remoting.

!Objects Instantiated Remotely Are Returned by Reference and Accessed by the Client Through a Proxy

!Remote Call Parameters, Return Values, and Fields Can Be:

#Marshal-by-value objects – A copy of the object is passed from one AppDomain to another

-Value types and classes that are serializable

#Marshal-by-reference objects – A reference to the object is passed from one AppDomain to another

-Classes that derive from the System.MarshalByRefObject class

#Not-marshaled objects – Objects suitable for local use only

-Any class that is not Marshal-By-Value or Marshal-By-Reference

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Because calls to a remote object can cause other objects to be passed across a remoting boundary, you should understand how objects are marshaled in .NET Remoting.

Inside the remoting boundary of the caller, for example, inside a single application domain, objects are passed by reference, and primitive data types are passed by value. Application domains are hard boundaries. Applications running in different application domains share no information, no global variables, and no static fields on classes. As mentioned in Remoting in this module, .NET Remoting is used to communicate between objects in different application domains.

All objects that are instantiated remotely are returned by reference. When a client instantiates a remote object, it receives a proxy to the class instance on the server. All methods that are called on the proxy are automatically forwarded to the remote class, and any results are returned to the client.

The following examples show scenarios where objects are passed across remoting boundaries because of calls to remote objects:

! Object parameters in a method call, such as myObj in: public int myRemoteMethod (MyRemoteObject myObj)

!Object return values of method calls, such as MyRemoteObject instances in:

public MyRemoteObject myRemoteMethod(String myString)

!Objects that result from property or field access of a remote object, such as instances that are accessed in the myNestedObject field of myObj in:

myObj.myNestedObject

All objects in the .NET Framework fall into three general remoting categories: marshal-by-value, marshal-by-reference, and not-marshaled.

12

Module 13: Remoting and XML Web Services

Marshal-By-Value Objects

Marshal-by-value objects include value types and classes that are serializable. A copy of such marshal-by-value objects is passed from one application domain to another.

You should use marshal-by-value objects when you need to move the complete state of the object with the execution to the target application domain for performance or processing purposes. In many scenarios, marshal-by-value objects reduce boundary crossing, such as network, process, and application domain roundtrips. Marshal-by-value objects have no distributed identity, and no proxy is ever created to reference them, as shown in the following example:

[Serializable] class Foo1A

{

//. . .

}

To participate in its own serialization when it is marshaled across application domain boundaries, an object can expose the ISerializable interface, as in the following example:

using System.Runtime.Serialization; //...

[Serializable]

class Foo1B : ISerializable

{

//. . .

}

Marshal-By-Reference Objects

References to marshal-by-reference objects are made when the object reference (ObjRef) is passed from one application to another. When the object reference arrives in the remote application, it is converted to a proxy back to the original object. The original object remains in the application domain in which it was created. A marshal-by-reference object’s class must derive from the

System.MarshalByRefObject class.

Use marshal-by-reference objects when an object’s state should remain in the application domain in which it was created and when only references to that object should be marshaled at the time that the object is remoted. For example, make a file object, whose internal representation contains a field that is an operating system handle, application domain-bound. In this case, the operating system handle would not be useful or appropriate in another application domain, process, or computer.

All operations on a marshal-by-reference object are appropriately indirected so that the common language runtime can intercept and forward them. This indirection applies to fields, properties, and methods of marshal-by-reference objects. For this reason, the performance overhead of marshal-by-reference objects is greater than the performance overhead of marshal-by-value objects.

Module 13: Remoting and XML Web Services

13

 

 

 

The following example declares a class Foo2 that is marshal-by-reference:

class Foo2 : MarshalByRefObject

{

//. . .

}

Not-Marshaled Objects

Not-marshaled objects are the default for all objects that do not derive from

System.MarshalByRefObject and that do not have the [Serializable] custom attribute. The use of not-marshaled objects is appropriate when an object should not leave the application domain because the object was designed for local use only, as in the following example:

class Foo3

{

//. . .

}

14

Module 13: Remoting and XML Web Services

Server Side

Topic Objective

To explain how to register and activate a remote object from the server side.

Lead-in

Remote objects must be registered with the remoting framework before clients can access them.

!Register the Channel

!Register Remote Objects by Using:

#The RegisterWellKnownServiceType call

RemotingConfiguration.RegisterWellKnownServiceType(

RemotingConfiguration.RegisterWellKnownServiceType(

typeof(HelloServer),

typeof(HelloServer),

"SayHello",

"SayHello",

WellKnownObjectMode.SingleCall);

WellKnownObjectMode.SingleCall);

# Or a configuration file

RemotingConfiguration.Configure("MyHello.exe.config");

RemotingConfiguration.Configure("MyHello.exe.config");

*****************************ILLEGAL FOR NON-TRAINER USE******************************

All remote objects must be registered with the remoting framework before clients can access them. Object registration is usually performed by a hosting application that starts up, registers one or more channels with ChannelServices, registers one or more remote objects with RemotingServices, and then waits until it is terminated.

Note The registered channels and objects are available only while the process that registered them is alive. When the process terminates, all channels and objects that are registered by this process are automatically removed from the remoting services where they were registered.

The following information is required when you register a remote object with the remoting framework:

!The type name of the remote object

!The object Uniform Resource Identifier that clients will use to locate the object

!For server-side activation, the object mode that is required

• The object mode can be single call or singleton.

Module 13: Remoting and XML Web Services

15

 

 

 

Methods of Remote Object Registration

You can register a remote object by calling

RemotingConfiguration.RegisterWellKnownServiceType, and passing the information that is described in the preceding list as parameters, or by storing that information in a configuration file and then calling RemotingConfiguration.Configure and passing the name of the configuration file as a parameter.

RegisterWellKnownServiceType and Configure perform the same function, but Configure is more convenient to use because the contents of the configuration file can be altered without recompiling the host application.

RegisterWellKnownServiceType

The following example code shows how to register the HelloServer class as a

SingleCall remote object by using the RegisterWellKnownServiceType method.

RemotingConfiguration.RegisterWellKnownServiceType(

typeof(HelloServer),

"SayHello",

WellKnownObjectMode.SingleCall);

In the preceding example, RemotingSamples.HelloServer is the name of the class, and SayHello is the object Uniform Resource Identifier.

Configuration File

The following example code shows how to register the HelloServer class as a

SingleCall remote object by using the Configure method:

RemotingConfiguration.Configure("MyHello.exe.config");

In the preceding example, the configuration file, MyHello.exe.config stores the same registration information that is stored in the parameters of the preceding

RegisterWellKnownServiceType method.

The format of the .NET Remoting configuration file is described in Remoting

Configuration Files in this module.

When the remote object in the preceding example is registered, the remoting framework creates an object reference and then extracts the required metadata about the object from the assembly. The object’s required metadata, the Uniform Resource Identifier, and the assembly name are then stored in the object reference, which is filed in a remoting framework table that is used for tracking registered remote objects.

Note The remote object itself is not instantiated by the registration process. Instantiation occurs only when a client attempts to call a method on the object or activates the object from the client side.

16

Module 13: Remoting and XML Web Services

Client Side

Topic Objective

To explain how to register and activate a remote object from the client side.

Lead-in

On the client side, a client registers the channel and activates the remote object.

! Register the Channel

ChannelServices.RegisterChannel(new TcpChannel());

ChannelServices.RegisterChannel(new TcpChannel());

!Activate Remote Object by Using:

#Activator.GetObject

HelloServer obj = (HelloServer)Activator.GetObject( HelloServer obj = (HelloServer)Activator.GetObject(

typeof(RemotingSamples.HelloServer),

typeof(RemotingSamples.HelloServer),

"tcp://localhost:8085/SayHello");

"tcp://localhost:8085/SayHello");

# new and a configuration file

RemotingConfiguration.Configure("MyHello.exe.config");

RemotingConfiguration.Configure("MyHello.exe.config");

HelloServer obj = new HelloServer();

HelloServer obj = new HelloServer();

*****************************ILLEGAL FOR NON-TRAINER USE******************************

On the client side, a client registers the channel and activates the remote object.

Registering the Channel

A client must first register the channel by calling ChannelServices.RegisterChannel. As previously mentioned in Server Side in this module, the server must first have registered the selected channel.

The following code example shows how to register a TCP Channel:

ChannelServices.RegisterChannel(new TcpChannel());

Important You do not specify a port number when you register the client channel.

Activating Remote Objects

After the client registers the channel, it can then activate the remote object by using GetObject or the new operator. It is important to note that the object is not instantiated when either of these calls is made. Actually, no network calls are generated at all. The remoting framework obtains enough information from the metadata to create the proxy without connecting to the remote object. A network connection is only established when the client calls a method on the proxy.

When the call arrives at the server, the remoting framework extracts the Uniform Resource Identifier from the message, examines the remoting framework tables to locate the reference for the object that matches the Uniform Resource Identifier, and then instantiates the object if necessary, forwarding the method call to the object. If the object is registered as SingleCall, it is destroyed after the method call is completed. For each method that is called, a new instance of the object is created.

Соседние файлы в папке c#