3.2 Pass Objects Across Application Domain Boundaries


Problem

You need to pass objects across application domain boundaries as arguments or return values.

Solution

Use marshal- by-value or marshal-by-reference objects.

Discussion

The .NET Remoting system (discussed in Chapter 12) makes passing objects across application domain boundaries straightforward. However, to those unfamiliar with .NET Remoting, the results can be very different from those expected. In fact, the most confusing aspect of using multiple application domains stems from the interaction with .NET Remoting and the way objects traverse application domain boundaries.

All types fall into one of three categories: nonremotable, marshal-by-value (MBV), or marshal-by-reference (MBR). Nonremotable types can't cross application domain boundaries and can't be used as arguments or return values in cross-application domain calls. Nonremotable types are discussed in recipe 3.4.

MBV types are serializable types. When you pass an MBV object across an application domain boundary as an argument or return value, the .NET Remoting system serializes the object's current state, passes it to the destination application domain, and creates a new copy of the object with the same state as the original. This results in a copy of the MBV object existing in both application domains. The two instances are initially identical, but they are independent; changes made to one instance are not reflected in the other instance. Here's an example of a serializable type named Employee that's passed by value across application domain boundaries. (See recipe 16.1 for details about creating serializable types.)

 [System.Serializable] public class Employee {          // Member implementations      } 

MBR types are those classes that derive from System.MarshalByRefObject . When you pass an MBR object across an application domain boundary as an argument or return value, the .NET Remoting system creates a proxy in the destination application domain that represents the remote MBR object. To any class in the destination application domain, the proxy looks and behaves like the remote MBR object that it represents. In reality, when a call is made against the proxy, the .NET Remoting system transparently passes the call and its arguments to the remote application domain and issues the call against the original object. Any results are passed back to the caller via the proxy. Here's a version of the Employee class that's passed by reference instead of by value. (See recipe 12.7 for details on how to create MBR types.)

 public class Employee : System.MarshalByRefObject {     // Member implementations      } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net