I couldn’t come up with a decent title for this post, so I just spit out some keywords.
We got an error today, stating the Controller of some object we wanted to put on CallContext needed to be serializable. Not thinking about the weird content of this error, we tried what would happen if we made the controller serializable. We now got a different error, which was even more weird:
Unhandled Exception: System.Security.SecurityException: Type System.DelegateSerializationHolder and the types derived from it (such as System.DelegateSerializationHolder) are not permitted to be deserialized at this security level.
This error occured when I tried to put some object on the CallContext by calling CallContext.SetData. We remembered the controller needing to be serializable, while it wasn’t remoted or anything. After some investigation, I found the problem. When you put an object on CallContext, be sure it doesn’t have any other objects attached to it through events. Because these events kind of ‘bind’ the objects together, so the object which subscribed to the event is sent also! We implemented ICloneable and put the clone on the CallContext: this solved the problem.
Oh yeah: MemberwiseClone copies the events and their handlers also. So this is NOT the way to implement the Clone() method. You will have to set each property individually on a new instantiation of the class. We’re working on a reflection-implementation which will take away the need to copy each property individually in code, but to let a method do this for you. If this turns out to be interesting, I’ll post it here.