Massimo Zerbini
Massimo Zerbini

Reputation: 3191

How to determine the interfaces that can be used to cast a MarshalByRefObject?

Is it possible to determine the interfaces that can be used to cast a MarshalByRefObject object?

How does the cast operator work with MarshalByRefObject objects? Does it call the CreateObjRef method?

Thanks, Massimo

Upvotes: 2

Views: 2113

Answers (2)

Massimo Zerbini
Massimo Zerbini

Reputation: 3191

Here's a workaround that can be used to retrieve the list of interfaces.

Define a public interface IDescriptor

public interface IDescriptor
{
   List<string> GetInterfaces();
}

Define a base class that implements the interface:

public class BaseMasrhalByRefObject : MasrhalByRefObject, IDescriptor
{
   public BaseMasrhalByRefObject() : base() {}

   public List<string> GetInterfaces()
   {
      List<string> types = new List<string>();
      foreach(Type i in GetType().GetInterfaces())
      {
         types.Add(i.AssemblyQualifiedName);
      }
      return types;
   }
}

Than use the BaseMasrhalByRefObject instead of MasrhalByRefObject to define a service object:

public class MyServiceObject : BaseMasrhalByRefObject, MyInterface1, MyInterface2, ...
{
      // Add logic method
}

In AppDomain A create the reference object of MyServiceObject. In AppDomain B get the proxy of the remote object. The proxy can be cast to IDescriptor:

public List<Type> GetInterfaces(MasrhalByRefObject proxy)
{
   List<Type> types = new List<Type>();
   IDescriptor des = proxy as IDescriptor;
   if (des != null)
   {
      foreach(string t in des.GetInterfaces()) // this is a remote call
      {
         types.Add(Type.GetType(t);
      }
   }
   return types;
}

Upvotes: 2

Bartosz W&#243;jtowicz
Bartosz W&#243;jtowicz

Reputation: 1401

MarshalByRefObject is a class so having only an interface you can't be sure if all classes implementing it derive from MarshalByRefObject. However, if you have an instance of an object you can easily check that using this expression:

if (obj1 is MarshalByRefObject)
{
    // do your thing
}

Upvotes: 0

Related Questions