Last active
August 29, 2015 14:24
-
-
Save theor/168463ce9be344625f43 to your computer and use it in GitHub Desktop.
Castle Dynamic Proxy sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Castle.DynamicProxy; | |
namespace ProxyTest | |
{ | |
public class Interceptor : IInterceptor | |
{ | |
private object _Target; | |
public void Intercept(IInvocation invocation) | |
{ | |
Console.ForegroundColor = ConsoleColor.Cyan; | |
Console.WriteLine("Before {0} Target: '{1}'", invocation.Method.Name, _Target); | |
Console.ResetColor(); | |
if (_Target != null) | |
{ | |
// we have a target, let's use it and forward the call | |
IChangeProxyTarget changeTarget = (IChangeProxyTarget)invocation; | |
changeTarget.ChangeInvocationTarget(_Target); | |
invocation.Proceed(); | |
} | |
else | |
{ | |
// no target, will provide a default value. | |
// this will work for methods and getters (which have return type) | |
// setter won't do anything | |
// ref/out params will need more logic - there's a setArgumentValue method in invocation, could do the trick. | |
if (invocation.Method.ReturnType != typeof(void)) | |
invocation.ReturnValue = Activator.CreateInstance(invocation.Method.ReturnType); | |
} | |
} | |
public void ChangeInvocationTarget(object target) | |
{ | |
_Target = target; | |
} | |
} | |
public interface IThing | |
{ | |
int I { get; } | |
int Compute(int i); | |
} | |
class Thing : IThing | |
{ | |
public int I { get { return 7; } } | |
public int Compute(int i) | |
{ | |
return 2 * i; | |
} | |
} | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
ProxyGenerator _generator = new ProxyGenerator(); | |
var interceptors = new Interceptor(); | |
// no invocation target at first - the interceptor will provide default return values | |
IThing t = (IThing)_generator.CreateInterfaceProxyWithTargetInterface(typeof(IThing), (Thing)null, interceptors); | |
Console.WriteLine(t.I); | |
Console.WriteLine(t.Compute(42)); | |
// provide an actual invocation target, the interceptor will forward its calls from now on | |
interceptors.ChangeInvocationTarget(new Thing()); | |
Console.WriteLine(t.I); | |
Console.WriteLine(t.Compute(42)); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment