Calling the instance of a ContextBoundObject

ContextBoundObjects are useful for implementing Aspect Orientated Programming (AOP), however one thing that I wanted to do was to call methods on the instance that the context "shadows". Since it caused me some pain I though I’d publish it here to avoid others suffering as I did.
1. Save the MarshalByRefObject that is passed into the AttributeContext, this represents the object that we’re shadowing

public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)

2. Assuming you can put your AOP attribute on any class, you’ll need to get hold of the type that is really inside the Marshalled object. There are a number of ways of doing this, this was the first mechanism I tried and it worked so I left it at this


void Postprocess(IMessage msg, IMessage msgReturn)



3. Marshal the object into the discovered type and call methods on it. All done.


sourceType = Type.GetType(typeName);

ObjRef objectRef = RemotingServices.Marshal(this.sourceMarshalByRefObject,null,sourceType);

object o = Activator.GetObject(sourceType, objectRef.URI);

if (o is IMyKnownInterface)


IMyKnownInterface myInterface = (IMyKnownInterface)o;



2 thoughts on “Calling the instance of a ContextBoundObject

  1. Thomas Danecker May 3, 2007 / 10:05 am

    I\’m just calling "obj as IMyKnownInterface" in the GetObjectSink method and it works also

  2. Paulio May 3, 2007 / 9:46 pm

    Yes, as soon as you have the obj you can make calls on it. The problem I had was that I wanted to make calls during the post process rather than the point of "sinking" where it doesn\’t seem that the obj is available. I still a little suprised this is the only point you can get a reference to the instance, but there you go.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s