Skip to content

Instantly share code, notes, and snippets.

@NtFreX
Created May 31, 2018 11:55
Show Gist options
  • Save NtFreX/5f89bf5ed317c92b41be8631c9647e16 to your computer and use it in GitHub Desktop.
Save NtFreX/5f89bf5ed317c92b41be8631c9647e16 to your computer and use it in GitHub Desktop.
public class MessagePumpProxy<T> : RealProxy
{
private readonly T _instance;
private readonly MessagePumpDispatcher _messagePumpDispatcher;
private MessagePumpProxy(T instance)
: base(typeof(T))
{
_instance = instance;
_messagePumpDispatcher = new MessagePumpDispatcher();
}
public static T Create(T instance)
{
return (T)new MessagePumpProxy<T>(instance).GetTransparentProxy();
}
public override IMessage Invoke(IMessage msg)
{
var methodCall = (IMethodCallMessage)msg;
var method = (MethodInfo)methodCall.MethodBase;
return _messagePumpDispatcher.Dispatch(() =>
{
try
{
var result = method.Invoke(_instance, methodCall.InArgs);
return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
}
catch (Exception e)
{
if (e is TargetInvocationException && e.InnerException != null)
{
return new ReturnMessage(e.InnerException, (IMethodCallMessage)msg);
}
return new ReturnMessage(e, (IMethodCallMessage)msg);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment