For a project we are using Unity 2.0 interception with policy injection to create and manage our NHibernate session. Therefore we created a custom ICallHandler in combination with a HandlerAttribute.
Problem is, that this policy injection call handler executed twice when we expect that it only executes once. It took us some time to figure out what caused the problem. The reason was that the InterceptionExtension was registered twice:
[AttributeUsage(AttributeTargets.Method)] public class NHibernateUnitOfWorkHandlerAttribute : HandlerAttribute { private bool _createTransaction; public NHibernateUnitOfWorkHandlerAttribute(bool createTransaction=false) { _createTransaction = createTransaction; } public override ICallHandler CreateHandler(IUnityContainer container) { return new NHibernateUnitOfWorkHandler(Order,_createTransaction); } } public class NHibernateUnitOfWorkHandler : ICallHandler { public NHibernateUnitOfWorkHandler(int order,bool createTransaction) { this.Order = order; this.CreateTransaction = createTransaction; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn result=null; try { using (var uow = DataFactory.CreateUnitOfWork(TransactionMode.Explicit)) { if (CreateTransaction) { using (var tx = uow.CreateTransaction()) { result = getNext()(input, getNext); if (result.Exception == null) tx.Commit(); else tx.Rollback(); } } else { result = getNext()(input, getNext); } } } catch (Exception ex) { result = getNext()(input, getNext); result.Exception = ex; } return result; } public int Order { get; set; } public bool CreateTransaction { get; set; } }
Problem is, that this policy injection call handler executed twice when we expect that it only executes once. It took us some time to figure out what caused the problem. The reason was that the InterceptionExtension was registered twice:
- One time explicitly through registration by using the AddNewExtension<T> method on the Unity container.
- One time implicitly by registering the EnterpriseLibraryCoreExtension which also adds the Interception extension.