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

private

void Postprocess(IMessage msg, IMessage msgReturn)

…msg.Properties[

"__TypeName"];

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

Type

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;

myInterface.MyMethod()

 
Advertisements
This entry was posted in cSharp. Bookmark the permalink.

2 Responses to Calling the instance of a ContextBoundObject

  1. Thomas Danecker says:

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

  2. Paulio says:

    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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s