Cross AppDomain Exception serialization
.net, appdomain, c#, exception, serialization
Solution
I found! Override GetObjectData to change the exception type :
[Serializable]
public class CommonException : Exception
{
public CommonException() { }
public CommonException(string message)
: base(message) { }
public CommonException(string message, Exception inner)
: base(message, inner) { }
protected CommonException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{ }
public override void GetObjectData(
SerializationInfo info,
StreamingContext context)
{
if (context.State == StreamingContextStates.CrossAppDomain)
info.SetType(typeof(CommonException));
base.GetObjectData(info, context);
}
}
Problem
Given two app domain : in the first, Library1 and CommonLibrary are loaded. In the second Library2 and CommonLibrary are loaded. Library2 defines a Library2Exception that inherit from CommonException (defined in CommonLibrary). When I call, in the first AppDomain, a method on a MarshallByRef of the second AppDomain that throws a Library2Exception, a SerializationException is thrown. Indeed, .Net tries to deserialize Library2Exception but this type is defined in Library2 which is not found in the first AppDomain. I want it to become a CommonException that I can handle. So, my questions are : - How can we control serialization between AppDomain like a SerializationBinder would do on a BinaryFormatter? - Is it possible to have an exception ByRef instead of ByValue (serialized) ?