// 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 Castle.Core; using Castle.DynamicProxy; namespace E { public interface IDirty { bool Dirty { get; set; } } public class Data : IDirty { public virtual int Iv { get; set; } public virtual string Sv { get; set; } public bool Dirty { get; set; } } public static class DirtyWrapper { internal class DirtyWrapperInterceptor : IInterceptor { public void Intercept(IInvocation inv) { if(inv.Method.IsSpecialName && inv.Method.Name.StartsWith("set_")) { ((IDirty)inv.Proxy).Dirty = true; } inv.Proceed(); } } public static T DirtyWrap(this ProxyGenerator gen, T o) where T : class { return gen.CreateClassProxyWithTarget(o, new IInterceptor[] { new DirtyWrapperInterceptor() }); } } public class Program { public static void Main(string[] args) { ProxyGenerator gen = new ProxyGenerator(); // change base object Data o = new Data(); Console.WriteLine(o.Iv + " " + o.Sv + " " + o.Dirty); o.Iv = 123; o.Sv = "ABC"; Console.WriteLine(o.Iv + " " + o.Sv + " " + o.Dirty); // change wrapped object Data o2 = new Data(); Console.WriteLine(o2.Iv + " " + o2.Sv + " " + o2.Dirty); o2 = gen.DirtyWrap(o); o2.Iv = 123; o2.Sv = "ABC"; Console.WriteLine(o2.Iv + " " + o2.Sv + " " + o2.Dirty); } } }