Using a dynamic proxy for NHibernate objects

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)
    {
        // Do something to record changes
        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:

// I would imagine an instance of Auditor being created implicitly
ICriteria criteria = session.CreateCriteria(typeof(Pet));
criteria.Add(Expression.Expression.Eq("Name", "Muffles"));

// return a list of Pet proxies instead
// so changes can be recorded.
IList<Pet> result = criteria.List<Pet>();

Pet aPet = result[0];
aPet.Age = aPet.Age + 1;

// I expect this to succeed since the proxy is still a Pet instance
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>). , , .

, , - - - , , .

, ,

+3
2

NHibernate Event Listeners.

NHibernate . , , - -.

.

+3

. ProxyFactoryFactory (nice name =)) NHibernate .

ProxyFactoryFactory .

, .

0

Source: https://habr.com/ru/post/1720443/


All Articles