In my previous post, A ghostly proxy, I talked about the Ghost Proxy Objects and the Interceptor pattern. This project was a result of a quick Spike I did for a personal project surrounding dynamic object generation (e.g. Ghost Objects). Although this could have gone further, it should allow you to Proxy many simple interfaces.
Implementing this is pretty easy... Here is a quick walk-through:
1. Download the source code (SmellyProxy.zip (27.4 kb)) and compile the solution
2. In the consuming application, add a reference to "Smelser.Proxy.dll"
3. Import the namespace into the consuming class file
using Smelser.Proxy;
Create Proxies for Interfaces and Abstract Classes
4. To create a proxy instance from a public Interface call the ProxyGenerator
IFoo proxyFromInterface = ProxyGenerator.CreateProxy<IFoo>();
5. You can also generate proxy instances for Generic Interfaces
IFoo proxyFromGenericInterface = ProxyGenerator.CreateProxy<IGenericFoo<string>>();
6. You can also generate a proxy Type for a given Interface
IFoo proxyFromGenericInterface = ProxyGenerator.CreateProxyType<IFoo>();
Create Proxies with Basic Intercept Support for inheritable Classes
7. You can also generate a proxy Type for a given Interface
Bar proxyFromGenericInterface = ProxyGenerator.CreateInterceptableProxy<Bar>();
8. To intercept a property action (e.g. get or set) or a method call, register a delgate to be called prior to execution of the target action, after it, or both. Although this is set on an instance it is retained for all subsequent intercept instances generated for that Type.
var classInterceptProxy = ProxyGenerator.CreateInterceptableProxy<Bar>();
foreach (var info in typeof(Bar).GetMethods(BindingFlags.Public |
BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
((IInterceptableProxy)classInterceptProxy)
.AddInterceptMethod(info, BeginAction, EndAction);
}
private static void BeginAction(object[] parameters)
{
Console.WriteLine("Begin action called");
}
private static void EndAction(object[] parameters, object returnValue)
{
Console.WriteLine("End action called return value of '{0}'", returnValue == null ?
"(is null)" : returnValue.ToString());
}
9. To remove proxy routines call RemoveInterceptMethod or ClearInterceptMethods on any instance of an Interceptable Proxy Type.
10. To determine if a Type is interceptable, test for the interface IInterceptableProxy.
That's it...