1: public class NHibernateSession : IDisposable
2: {
3: private readonly ITransaction _transaction;
4: private readonly IDbConnection _connection;
5:
6: public NHibernateSession(bool beginTran, IDbConnection connection = null)
7: {
8: if (connection != null && connection.State == ConnectionState.Closed)
9: {
10: connection.Open();
11: _connection = connection;
12: }
13:
14: if (CurrentSessionContext.HasBind(NHibernateBootstrapper.SessionFactory))
15: {
16: NHibernateWorkspace.CurrentSession = NHibernateBootstrapper.SessionFactory.GetCurrentSession();
17: }
18: else
19: {
20: NHibernateWorkspace.CurrentSession = connection != null ?
21: NHibernateBootstrapper.SessionFactory.OpenSession(connection) :
22: NHibernateBootstrapper.SessionFactory.OpenSession();
23:
24: CurrentSessionContext.Bind(NHibernateWorkspace.CurrentSession);
25: }
26: if(beginTran)
27: _transaction = NHibernateWorkspace.CurrentSession.BeginTransaction();
28: }
29:
30: public NHibernateSession(int customerId, string connString) : this(false, new SqlConnection(connString))
31: {
32: var sql = string.Format("USE FEDERATION Customer_Federation(CustID = {0}) WITH RESET, FILTERING = ON;", customerId);
33: var query = NHibernateWorkspace.CurrentSession.CreateSQLQuery(sql);
34: query.UniqueResult();
35: _transaction = NHibernateWorkspace.CurrentSession.BeginTransaction();
36: }
37:
38: public NHibernateSession(): this(true)
39: {
40:
41: }
42:
43: public void Dispose()
44: {
45: Dispose(true);
46: GC.SuppressFinalize(this);
47: }
48:
49: // The bulk of the clean-up code is implemented in Dispose(bool)
50: protected virtual void Dispose(bool disposing)
51: {
52: if (disposing)
53: {
54: try
55: {
56: if(_transaction != null)
57: _transaction.Commit();
58: if(_connection != null && _connection.State != ConnectionState.Closed)
59: _connection.Close();
60: }
61: catch
62: {
63: if (_transaction != null)
64: _transaction.Rollback();
65: throw;
66: }
67: finally
68: {
69: // free managed resources
70: CurrentSessionContext.Unbind(NHibernateBootstrapper.SessionFactory);
71: NHibernateWorkspace.CurrentSession.Dispose();
72: }
73: }
74: }
75: }