Thanks a lot for your answer.
I've followed your directions and used your tutorial on mixins and
finally get the result.
But I'm not sure if there is a better way, particularly to improve the
way the properties values are imported in
"ImportPublicReadWritePropertiesValues".
- So here is the core, "ISelectable.cs" :
[code]using Castle.DynamicProxy;
namespace TestCastleDynamicProxy
{
public interface ISelectable
{
bool IsSelected
{
get;
set;
}
}
public class ISelectableFactory
{
private class SelectableDefaultImplementation : ISelectable
{
public bool IsSelected
{
get;
set;
}
}
private static readonly ProxyGenerator proxyGenerator;
static ISelectableFactory()
{
proxyGenerator = new ProxyGenerator();
}
public static ISelectable New(object entity)
{
ProxyGenerationOptions options = new ProxyGenerationOptions
();
options.AddMixinInstance(new
SelectableDefaultImplementation());
ISelectable selectableEntity =
proxyGenerator.CreateClassProxy(entity.GetType(), null, options) as
ISelectable;
selectableEntity.IsSelected = false;
selectableEntity.ImportPublicReadWritePropertiesValues
(entity);
return selectableEntity;
}
}
}[/code]
- It uses this extension class to import properties values,
"ReflectionExtensions.cs" :
[code]using System.Reflection;
namespace TestCastleDynamicProxy
{
public static class ReflectionExtensions
{
public static void ImportPublicReadWritePropertiesValues(this
object to, object from)
{
if (to != null && from != null)
{
foreach (PropertyInfo property in from.GetType
().GetProperties())
{
MethodInfo propertyGetter = property.GetGetMethod
();
// Ensure that the property can be retrieved from
the source, ie that it is not write-only
if (propertyGetter != null)
{
MethodInfo propertySetter = to.GetType
().GetProperty(property.Name).GetSetMethod();
// Ensure that the property can be set on the
target, ie that it is not read-only.
if (propertySetter != null)
{
propertySetter.Invoke(to, new object[]
{ propertyGetter.Invoke(from, null) });
}
}
}
}
}
}
}[/code]
- Some business entities, "Business.cs" :
[code]namespace TestCastleDynamicProxy
{
public class A
{
public int N
{
get;
set;
}
}
public class B
{
public int M
{
get;
set;
}
}
}[/code]
- And finally the mix of all these things, "Program.cs" :
[code]namespace TestCastleDynamicProxy
{
class Program
{
static void Main(string[] args)
{
A a = new A
{
N = 1
};
B b = new B
{
M = 1
};
ISelectable selectableA = ISelectableFactory.New(a);
selectableA.IsSelected = true;
int n = (selectableA as A).N;
ISelectable selectableB = ISelectableFactory.New(b);
int m = (selectableB as B).M;
}
}
}[/code]
The casts of "selectableA" and "selectableB" to "A" and "B"
respectively don't return "null" and "N" and "M" have the good values.
Please share your opinion.
Thanks again.