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()
…
I\’m just calling "obj as IMyKnownInterface" in the GetObjectSink method and it works also
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.