28 October 2008

castle dynamic proxy

on a lark, i decided to play with the castle dynamic proxy library. it was fairly easy to use it to create a simple extension method to broadcast method invocations to all elements of a list. it will even work with property setters and other extension methods, provided each is virtual. now is the (next) time i hate the fact that methods are sealed by default.


public static T Broadcast<T>(this IEnumerable<T> items) {
  return new ProxyGenerator().CreateClassProxy<T>(new BroadcastInterceptor<T>(items));
}


private class BroadcastInterceptor<T> : IInterceptor {
  private readonly IEnumerable<T> items;

  public BroadcastInterceptor(IEnumerable<T> items) {
    this.items = items;
  }

  public void Intercept(IInvocation invocation) {
    foreach (var t in items) {
      invocation.Method.Invoke(t, invocation.Arguments);
    }
  }
}


var a = new TestObject();
var b = new TestObject();
List<TestObject> list = Quick.List(a, b);
list.Broadcast().Poke();

No comments:

Post a Comment