Created
January 14, 2013 19:23
-
-
Save jonnii/4532575 to your computer and use it in GitHub Desktop.
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; | |
using NUnit.Framework; | |
namespace ProxyMagic | |
{ | |
public class DataObject | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
public int Age { get; set; } | |
} | |
public interface IDataObject | |
{ | |
string FirstName { get; } | |
string LastName { get; } | |
int Age { get; } | |
} | |
public class ProxyInterceptor : IInterceptor | |
{ | |
private readonly object data; | |
public ProxyInterceptor(object data) | |
{ | |
this.data = data; | |
} | |
public void Intercept(IInvocation invocation) | |
{ | |
var method = invocation.Method; | |
var targetMethod = data.GetType().GetMethod(method.Name); | |
invocation.ReturnValue = targetMethod.Invoke(data, invocation.Arguments); | |
} | |
} | |
[TestFixture] | |
public class ProxyTest | |
{ | |
[Test] | |
public void Should() | |
{ | |
var data = new DataObject | |
{ | |
FirstName = "firstname", | |
LastName = "lastname", | |
Age = 30 | |
}; | |
var generator = new ProxyGenerator(); | |
var proxy = generator.CreateInterfaceProxyWithoutTarget<IDataObject>( | |
new ProxyInterceptor(data)); | |
Console.WriteLine(proxy.FirstName); | |
Console.WriteLine(proxy.LastName); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment