Intercepting method from abstract parent on derived instance using DynamicProxy
I have an object derived from an abstract base class and I want to intercept a method on the object.
Does DynamicProxy support this scenario? I seem to only be able to create proxies by interface or without target but not by abstract base class with a target
public abstract class Sandwich
{
public abstract void ShareWithFriend();
}
public sealed class PastramiSandwich : Sandwich
{
public override void ShareWithFriend()
{
throw new NotSupportedException("No way, dude");
}
}
class SandwichInterceptor : IIntercepto开发者_StackOverflow中文版r
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch (NotSupportedException)
{
// too bad
}
}
}
internal class Program
{
private static void Main()
{
var sandwich = new PastramiSandwich();
var generator = new ProxyGenerator();
// throws ArgumentException("specified type is not an interface")
var proxy1 = generator.CreateInterfaceProxyWithTarget<Sandwich>(
sandwich,
new SandwichInterceptor());
proxy1.ShareWithFriend();
// does not accept a target
var proxy2 = generator.CreateClassProxy<Sandwich>(
/* sandwich?, */
new SandwichInterceptor());
// hence the method call fails in the interceptor
proxy2.ShareWithFriend();
}
}
This works:
var proxy1 = generator.CreateClassProxyWithTarget<Sandwich>(
sandwich,
new SandwichInterceptor());
proxy1.ShareWithFriend();
精彩评论