using System.Collections.Generic;
using ProxyGenerator = Castle.DynamicProxy.ProxyGenerator;
using IInterceptor = Castle.DynamicProxy.IInterceptor;
namespace De.Tutorials.Training
public class DataModelProxyFactoryExample
public static void Main(string[] args)
IDataModel dataModel = DataModelProxyFactory.CreateDataModelProxyFor<IDataModel>();
dataModel.Data = "Hallo";
Console.WriteLine(dataModel.Data);
Console.WriteLine(dataModel.Value);
IGenericDataModel<string, IDataModel> genericDataModel = DataModelProxyFactory.CreateDataModelProxyFor<IGenericDataModel<string, IDataModel>>();
genericDataModel.Data = "Bubu";
genericDataModel.Value = dataModel;
Console.WriteLine(genericDataModel.Data);
Console.WriteLine(genericDataModel.Value.Data + " " + genericDataModel.Value.Value);
/// A simple DataModel Interface
public interface IDataModel
/// A simple GenericDataModel Interface
public interface IGenericDataModel<TData,TValue>
/// A Generic DataModel Proxy Factory
public class DataModelProxyFactory
public static TargetType CreateDataModelProxyFor<TargetType>()
ProxyGenerator proxyGenerator
= new ProxyGenerator
();
return (TargetType
)proxyGenerator.
CreateProxy(typeof(TargetType
),
new DataModelWrapper
(typeof(TargetType
)),
new object());
/// A simple DataModel wrapper
public class DataModelWrapper : IInterceptor
private IDictionary<string, object> dictionary;
private Type wrappedType;
public DataModelWrapper(Type wrappedType)
this.wrappedType = wrappedType;
this.
dictionary = new Dictionary
<string,
object>();
#region IInterceptor Members
public object Intercept(Castle.DynamicProxy.IInvocation invocation, params object[] args)
if (this.wrappedType.Equals(invocation.Method.DeclaringType))
if (invocation.Method.Name.StartsWith("get_"))
return dictionary[GetPropertyNameFor(invocation.Method.Name)];
else if (invocation.Method.Name.StartsWith("set_"))
dictionary[GetPropertyNameFor(invocation.Method.Name)] = args[0];
private string GetPropertyNameFor(string methodName)
return methodName.Substring(4);