Skip to content

Instantly share code, notes, and snippets.

@DavidBoike
Created December 22, 2011 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBoike/1510655 to your computer and use it in GitHub Desktop.
Save DavidBoike/1510655 to your computer and use it in GitHub Desktop.
Proof of concept for use of Castle Dynamic Proxy for question at http://stackoverflow.com/questions/8497111/framework-for-asp-net-data-binding-wrapper-classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
using System.Web.UI;
namespace DynamicProxyTest
{
class Program
{
static void Main(string[] args)
{
List<User> users = new List<User>();
users.Add(new User { FirstName = "John", LastName = "Doe" });
users.Add(new User { FirstName = "Jane", LastName = "Doe" });
var userProxies = users
.ProxyAddMixins(u => new UserProxyImpl { User = u })
.ToList();
Console.WriteLine("First\tLast\tFull");
foreach (var userProxy in userProxies)
{
Console.WriteLine("{0}\t{1}\t{2}",
DataBinder.Eval(userProxy, "FirstName"),
DataBinder.Eval(userProxy, "LastName"),
DataBinder.Eval(userProxy, "FullName"));
}
Console.ReadLine();
}
}
public class User
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
public interface IUserProxy
{
string FullName { get; }
}
public class UserProxyImpl : IUserProxy
{
public User User { get; set; }
public string FullName
{
get { return User.FirstName + " " + User.LastName; }
}
}
public static class ProxyExtensions
{
public static IEnumerable<T> ProxyAddMixins<T>(this IEnumerable<T> collection, params Func<T, object>[] mixinSelectors)
where T : class
{
ProxyGenerator factory = new ProxyGenerator();
foreach (T item in collection)
{
ProxyGenerationOptions o = new ProxyGenerationOptions();
foreach (var func in mixinSelectors)
{
object mixin = func(item);
o.AddMixinInstance(mixin);
}
yield return factory.CreateClassProxyWithTarget<T>(item, o);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment