Question

I set up an IInterceptor for ILoggable objects in my domain model. And on OnFlushDirty event, i am trying to save a log (audit). But while doing this, my code goes into an infinite loop.

_logrepository.Save(log) calls OnFlushDirty even if log is not an ILoggable object (it is because entity is still the previous object)

Is there a way to use .Save (without opening another session) in IInterceptor, or how do I insert a log into database in IInterceptor?


public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
    {
      //find diffs, log each change
      if (entity is ILoggable && entity is NamedEntity)
      {
        var namedEntity = entity as NamedEntity;
        for (var i = 0; i < currentState.Count(); i++)
        {
          if (currentState[i] != previousState[i])
          {
            var log = new Log()
                        {
                          Description = "update",
                          InDate = namedEntity.ModifiedDate.Value,
                          ItemId = namedEntity.Id,
                          ItemType = namedEntity.GetType().Name,
                          NewValue = currentState[i].ToString(),
                          OldValue = previousState[i].ToString(),
                          PropertyName = propertyNames[i],
                          UserId = namedEntity.ModifiedByUserId.Value
                        };

            // calling save calls onflushdirty again, where entity is not log, but the same entity of the first call
            ObjectFactory.GetInstance().Save(log);
          }
        }
      }
      return base.OnFlushDirty(entity, id, currentState, previousState, propertyNames, types);
    }
Was it helpful?

Solution

ok, i figured it out, my problem was _logrepository.Save(log) was opening ANOTHER transaction and commiting it. So, i changed logrepository.Save(log) not to open and commit another transaction but use an open transaction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top