tôi đã viết một ví dụ như thế nàyCách sử dụng IInterceptor trong Castle.DynamicProxy?
Simple lớp Calculator:
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
thực hiện "IInterceptor" được cung cấp bởi DynamicProxy
[Serializable]
public abstract class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
ExecuteBefore(invocation);
invocation.Proceed();
ExecuteAfter(invocation);
}
protected abstract void ExecuteAfter(IInvocation invocation);
protected abstract void ExecuteBefore(IInvocation invocation);
}
Tạo một lớp Interceptor và thừa hưởng từ "Interceptor" lớp
public class CalculatorInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("Start");
}
protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("End");
}
}
nhưng khi tôi sử dụng nó KHÔNG hoạt động !!!
static void Main(string[] args)
{
ProxyGenerator generator = new ProxyGenerator();
Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
var r = c.Add(11, 22);
Console.WriteLine(r);
Console.ReadKey();
}
tôi trừ để xem một cái gì đó như thế này:
START
33
END
nhưng chỉ hiển thị
33
Làm thế nào tôi có thể sửa chữa nó?!
vâng, có vẻ ok nhưng câu hỏi là kết quả là START END 33 cách tôi có thể đặt Trước & Sau theo cách chính xác và xem kết quả như thế này START 33 END, Tôi có thể sửa lỗi này trong lớp Interceptor cho các phương thức đúng không? – user3153878
@ user3153878 trình chặn thực thi ngay trước và sau khi gọi 'Add', nhưng bạn ghi kết quả sau đó vào bàn điều khiển (thực thi trước -> thi hành Add -> execute after -> write result). Nếu bạn tạo bảng điều khiển gọi trong phương thức 'Add', bạn sẽ nhận được kết quả mong muốn. –