Can I Use Generics in .NET Remoting?

By Ashish Khandelwal, July 25, 2010

Yes. You can expose generic types as remote objects, for example:

public class MyRemoteClass<T> : MarshalByRefObject
{...}
Type serverType = typeof(MyRemoteClass<int>);

RemotingConfiguration.RegisterWellKnownServiceType(serverType,
                                                   "Some URI",
                                                  WellKnownObjectMode.SingleCall);

Note that the specific type arguments used must be a marshalable type, that is, either serializable or derived from MarshalByRefObject. Consequently, a generic remote type will typically place a derivation constraint from MarshalByRefObject on its generic type parameters when expecting reference type parameters:

public class MyRemoteClass<T> : MarshalByRefObject where T : MarshalByRefObject
{...}

To administratively register a generic type, provide the type arguments in double square brackets.

For example, to register the class MyRemoteClass<T> with an integer, you should write:

<service>
   <wellknown type="MyRemoteClass[[System.Int32]],ServerAssembly"
              mode="SingleCall" objectUri="Some URI"/>
</service>

The double square brackets is required in case you need to specify multiple type arguments, in which case, each type arguments would be encased in a separate pair of brackets, separated by a comma. For example, to register the class MyRemoteClass<T,U> with an integer and a string, you would write:

<service>
   <wellknown type="MyRemoteClass[[System.Int32],[System.String]],
                     ServerAssembly" mode="SingleCall" objectUri="Some URI"/>
</service>

Creating a new instance of generic remote objects is done just as with non-generic remote objects.

VN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)

Leave a Reply