Please see the code below, which is a Unit of Work class:
using System;
using System.Collections.Generic;
using System.Data;
using NHibernate;
namespace UnitOfWork
{
public class NHUnitOfWork : IUnitOfWork
{
private ISession session;
private ITransaction transaction;
public ISession Session { get { return this.session; } }
public NHUnitOfWork() { }
public void OpenSession()
{
if (this.session == null || !this.session.IsConnected)
{
if (this.session != null)
this.session.Dispose();
this.session = NHSessionFactorySingleton.SessionFactory.OpenSession();
}
}
public void BeginTransation(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
{
if (this.transaction == null || !this.transaction.IsActive)
{
if (this.transaction != null)
this.transaction.Dispose();
this.transaction = this.session.BeginTransaction(isolationLevel);
}
}
public void Commit()
{
try
{
this.transaction.Commit();
}
catch
{
this.transaction.Rollback();
throw;
}
}
public void Rollback()
{
this.transaction.Rollback();
}
public void Dispose()
{
if (this.transaction != null)
{
this.transaction.Dispose();
this.transaction = null;
}
if (this.session != null)
{
this.session.Close();
this.session.Dispose();
session = null;
}
}
}
}
I took it from a github repository called UnitOfWork. I have integrated it into my application and it is working very nicely. However, I realise that the ISession class is not thread safe and I am trying to understand the implications of this.
Q1) Is there only a risk here if I manipulate the same Unit of Work instance in two different threads that I have created using the Thread class?
Q2) Would there be any issues using this in a web scenario i.e. where an ASP.NET MVC application uses the Unit of Work?
Q3) How can I make this class thread safe for all scenarios? I have looked at the NHibernation documentation page NHibernate and the Unit of Work Pattern - the last section talks about making the Unit of Work thread safe, however the approach seems like an overkill to me.
Aucun commentaire:
Enregistrer un commentaire