I am trying to use Castle.DynamicProxy2 for cleanup code inside NHibernate persistent classes. Here is a simple version.
Pet Class:
public class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
And its mapping file:
<class name="Pet" table="Pet">
<id name="Id" column="Id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="Name" column="Name"/>
<property name="Age" column="Age"/>
</class>
You need to check instances of the Pet class. Typically, the Name and Age properties would not be automatic properties and would contain logic for recording changes in values. Now I'm thinking of using proxies to implement audit logic in property settings. To do this, I created an auditor IInterceptor:
public class Auditor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
}
}
It is simple enough to create a valid instance of the Pet class using Castle.DynamicProxy2.
Pet aPet = proxyGenerator.CreateClassProxy<Pet>(new Auditor());
aPet.Name = "Muffles"; // The Auditor instance would record this.
aPet.Age = 4; // and this too...
. Pet , , Pet NHibernate. , NHibernate - Pet:
ICriteria criteria = session.CreateCriteria(typeof(Pet));
criteria.Add(Expression.Expression.Eq("Name", "Muffles"));
IList<Pet> result = criteria.List<Pet>();
Pet aPet = result[0];
aPet.Age = aPet.Age + 1;
session.Save(aPet);
- , :
ICriteria criteria = session.CreateCriteria(ProxyHelper.GetProxyType<Pet>());
criteria.Add(Expression.Expression.Eq("Name", "Muffles"));
// use List() instead of List<T>()
// and IList instead of IList<Pet>
IList results = criteria.List();
ProxyHelper.GetProxyType<Pet>() Pet-. , (, IList<Pet>). , , .
, , - - - , , .
, ,