// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using Castle.Core; using Castle.Core.Interceptor; using Castle.DynamicProxy; namespace E { public interface IFoobar { void Test(); } public class Foobar : IFoobar { public void Test() { Console.WriteLine("I am real"); } } public interface IFoobarDictionary : IFoobar, IDictionary { } public static class ProxyHelper { internal class InterfaceOnlyInterceptor : IInterceptor { public Delegate Del { get; set; } public void Intercept(IInvocation inv) { inv.ReturnValue = Del.DynamicInvoke(inv.Arguments); } } public static T InterfaceOnly(this ProxyGenerator gen, Action ac) where T : class { return (T)gen.CreateInterfaceProxyWithoutTarget(typeof(T), new InterfaceOnlyInterceptor { Del = ac }); } internal class ClassWrapInterceptor : IInterceptor { public Delegate Del1 { get; set; } public Delegate Del2 { get; set; } public void Intercept(IInvocation inv) { Del1.DynamicInvoke(); inv.Proceed(); Del2.DynamicInvoke(); } } public static T ClassWrap(this ProxyGenerator gen, T o, Action ac1, Action ac2) where T : class { return (T)gen.CreateInterfaceProxyWithTarget(typeof(T), o, new IInterceptor[] { new ClassWrapInterceptor { Del1 = ac1, Del2 = ac2 } }); } public static T3 CreateDictionaryWrap(this ProxyGenerator gen) where T1 : T2 where T3 : T2, IDictionary { ProxyGenerationOptions opt = new ProxyGenerationOptions(); opt.AddMixinInstance(new Dictionary()); return (T3)gen.CreateClassProxy(typeof(T1), new Type[] { typeof(T3) }, opt); } } public class Program { public static void Main(string[] args) { ProxyGenerator gen = new ProxyGenerator(); IFoobar o1 = gen.InterfaceOnly(() => Console.WriteLine("I am #1")); o1.Test(); IFoobar o2 = gen.InterfaceOnly(() => Console.WriteLine("I am #2")); o2.Test(); IFoobar o3 = new Foobar(); o3.Test(); IFoobar o4 = gen.ClassWrap(o3, () => Console.WriteLine("Before"), () => Console.WriteLine("After")); o4.Test(); IFoobarDictionary o5 = gen.CreateDictionaryWrap(); o5.Test(); o5.Add("k", "v"); Console.WriteLine(o5["k"]); } } }