标签:
Introduction?
Castle DynamicProxy is a library for generating lightweight .NET proxies on the fly at runtime. Proxy objects allow calls to members of an object to be intercepted without modifying the code of the class.
DynamicProxy differs from the proxy implementation built into the CLR which requires the proxied class to extend MarshalByRefObject. Extending MashalByRefObject to proxy an object can be too intrusive because it does not allow the class to extend another class and it does not allow transparent proxying of classes. Additionally Castle DynamicProxy provides capabilities beyond what standard CLR proxies can do, for example it lets you mix in multiple objects.
Requirements?
To use Castle DynamicProxy you need the following environment:
At this time Mono is not supported |
?
?
DynamicProxy assembly
In previous versions (up to v2.2) DynamicProxy used to live in its own assembly Castle.DynamicProxy.dll. It was later moved to Castle.Core.dll and now no other assembly is required to use it.
?
Interception pipeline?
Another way, and it‘s how DP is used mostly, is by adding behavior to the proxied objects. That‘s what the IInterceptor interface you‘ll find in DynamicProxy is for. You use interceptors to inject behavior into the proxy.
The picture above shows schematically how that works.
?
Interceptor example?
If this was not clear enough, here‘s a sample interceptor, that shows how it works:
[Serializable]
public class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Before target call");
try
{
invocation.Proceed();
}
catch(Exception)
{
Console.WriteLine("Target threw an exception!");
throw;
}
finally
{
Console.WriteLine("After target call");
}
}
}
Hopefully, at this stage you have a pretty good idea about what DynamicProxy is, how it works, and what it‘s good for. In the next chapter we‘ll dive into some more advanced capabilities, plugging into, and influencing the process of generating proxy class.
See also?
标签:
原文地址:http://www.cnblogs.com/teamleader/p/4296569.html