Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive/sources/HeuristicLab.Hive.New/HeuristicLab.Services.Hive.DataAccess/3.3/ContextFactory.cs @ 4593

Last change on this file since 4593 was 4593, checked in by cneumuel, 14 years ago

recreated basic project structure (#1233)

File size: 5.2 KB
RevLine 
[4593]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Data.Linq;
25using System.Threading;
26using System.Transactions;
27using HeuristicLab.Tracing;
28using HeuristicLab.Services.Hive.Common;
29using HeuristicLab.Services.Hive.DataAccess.Properties;
30
31
32namespace HeuristicLab.Services.Hive.DataAccess {
33  /// <summary>
34  /// This class handles creates one Context for each Thread which asks for one.
35  /// If one Thread calls GetContext several times, it always gets the same Context object.
36  /// A context object is removed from the cache when it is disposed.
37  ///
38  /// Every context has a DB-Transaction over its livetime. After using the context object
39  /// it has to be disposed in order to finish the corresponding transaction.
40  /// </summary>
41  public class ContextFactory : IContextFactory {
42    private static object locker = new object();
43    private static IDictionary<int, HiveDataContext> contexts = new Dictionary<int, HiveDataContext>();
44    private static IDictionary<int, TransactionScope> transactions = new Dictionary<int, TransactionScope>();
45
46    private static IContextFactory instance = null;
47    public static IContextFactory Instance {
48      get {
49        if (instance == null)
50          instance = new ContextFactory();
51        return instance;
52      }
53    }
54
55    #region IContextManager Members
56
57    public IDisposable GetContext() {
58      return GetContext(true);
59    }
60
61    public IDisposable GetContext(bool withTransaction) {
62      lock (locker) {
63        int threadId = Thread.CurrentThread.ManagedThreadId;
64
65        if (contexts.ContainsKey(threadId)) {
66          Logger.Error("ERROR: Context for this Thread already defined. Will dispose it and then create a new one.");
67          RemoveContext();
68          RemoveAndCompleteTransaction();
69        }
70
71        DisposableHiveDataContext context = CreateContext();
72        context.OnDisposing += new EventHandler(context_OnDisposing);
73        contexts.Add(threadId, context);
74
75        if (withTransaction) {
76          TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = ApplicationConstants.ISOLATION_LEVEL_SCOPE });
77          transactions.Add(threadId, transaction);
78        }
79        return context;
80      }
81    }
82
83    private static DisposableHiveDataContext CreateContext() {
84      return new DisposableHiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString);
85    }
86
87    void context_OnDisposing(object sender, EventArgs e) {
88      lock (locker) {
89        RemoveContext();
90        RemoveAndCompleteTransaction();
91      }
92    }
93
94    public void RollbackTransaction() {
95      int threadId = Thread.CurrentThread.ManagedThreadId;
96
97      TransactionScope transaction = transactions[threadId];
98      transaction.Dispose();
99    }
100
101    public void RemoveContext() {
102      lock (locker) {
103        int threadId = Thread.CurrentThread.ManagedThreadId;
104
105        contexts.Remove(threadId);
106        // context gets disposed implicitly, when it is used as IDisposable
107      }
108    }
109
110    public void RemoveAndCompleteTransaction() {
111      lock (locker) {
112        int threadId = Thread.CurrentThread.ManagedThreadId;
113
114        // context does not always have an associated transaction
115        if (transactions.ContainsKey(threadId)) {
116          try {
117            transactions[threadId].Complete();
118            transactions[threadId].Dispose();
119          }
120          catch (Exception) { }
121          finally {
122            transactions.Remove(threadId);
123          }
124        }
125      }
126    }
127
128    public DataContext CurrentContext {
129      get {
130        lock (locker) {
131          int threadId = Thread.CurrentThread.ManagedThreadId;
132          if (contexts.ContainsKey(threadId)) {
133            return contexts[threadId];
134          } else {
135            return null;
136          }
137        }
138      }
139    }
140
141    #endregion
142  }
143
144  /// <summary>
145  /// Offers an event when it gets disposed
146  /// </summary>
147  class DisposableHiveDataContext : HiveDataContext {
148
149    public DisposableHiveDataContext(string connection) : base(connection) { }
150
151    protected override void Dispose(bool disposing) {
152      base.Dispose(disposing);
153      if (OnDisposing != null)
154        OnDisposing(this, new EventArgs());
155    }
156
157    public event EventHandler OnDisposing;
158  }
159}
Note: See TracBrowser for help on using the repository browser.