Sometimes you would want to explicitly set dead lock priority as part of a transaction which is not possible if you are using NHibernate as of now. In such cases you can define a custom Interceptor which does the trick. Here is a small snippet of code that can help you achieve that:
1. sessionFactory.OpenSession will pass the interceptor to session.
2. OpenSession() verifies if there are any interceptors defined in this case it will be "DeadLockPriorityInterceptor".
3. Executes SetSession() as it is overridden by an interceptor.
4. session.BeginTransaction() will start the transaction.
5. BeginTransaction() verifies if an interceptor is defined by OpenSession().
6. Executes AfterTransactionBegin() as it is overridden by an interceptor.
That's it. NHibernate offers various interceptor points which will become quite handy at times.
“Simplicity, carried to the extreme, becomes elegance.” – Jon Franklin
public class DeadLockPriorityInterceptor : EmptyInterceptor { private ISession session; private string priority; public DeadLockPriorityInterceptor(string Priority) { priority = Priority; } public override void AfterTransactionBegin(ITransaction tx) { using (var command = session.Connection.CreateCommand()) { session.Transaction.Enlist(command); string sql = string.Format("SET DEADLOCK_PRIORITY {0}", priority); // Create a SQL Command //System.Data.IDbCommand command = session.Connection.CreateCommand(); // Set the query you're going to run command.CommandText = sql; // Run the query command.ExecuteNonQuery(); } } public override void SetSession(ISession sessionLocal) { session = sessionLocal; } }Now your interceptor is ready. So if you would like to set your deadlock priority to High (ie.. SET DEADLOCK_PRIORITY HIGH), then just use following single line of code shown below:
ISession session = sessionFactory.OpenSession(new DeadLockPriorityInterceptor("HIGH")); session.BeginTransaction()This is how it works
1. sessionFactory.OpenSession will pass the interceptor to session.
2. OpenSession() verifies if there are any interceptors defined in this case it will be "DeadLockPriorityInterceptor".
3. Executes SetSession() as it is overridden by an interceptor.
4. session.BeginTransaction() will start the transaction.
5. BeginTransaction() verifies if an interceptor is defined by OpenSession().
6. Executes AfterTransactionBegin() as it is overridden by an interceptor.
That's it. NHibernate offers various interceptor points which will become quite handy at times.
“Simplicity, carried to the extreme, becomes elegance.” – Jon Franklin