forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDebugConnectionProvider.cs
65 lines (59 loc) · 1.41 KB
/
DebugConnectionProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Concurrent;
using System.Data;
using System.Data.Common;
using System.Linq;
using NHibernate.Connection;
namespace NHibernate.Test
{
/// <summary>
/// This connection provider keeps a list of all open connections,
/// it is used when testing to check that tests clean up after themselves.
/// </summary>
public partial class DebugConnectionProvider : DriverConnectionProvider
{
private ConcurrentDictionary<DbConnection, byte> connections = new ConcurrentDictionary<DbConnection, byte>();
public override DbConnection GetConnection()
{
try
{
var connection = base.GetConnection();
connections.TryAdd(connection, 0);
return connection;
}
catch (Exception e)
{
throw new HibernateException("Could not open connection to: " + ConnectionString, e);
}
}
public override void CloseConnection(DbConnection conn)
{
base.CloseConnection(conn);
byte _;
connections.TryRemove(conn, out _);
}
public bool HasOpenConnections
=> connections.Keys.Any(IsNotClosed);
private static bool IsNotClosed(DbConnection conn)
{
try
{
return conn.State != ConnectionState.Closed;
}
catch (ObjectDisposedException)
{
return false;
}
}
public void CloseAllConnections()
{
while (connections.Count != 0)
{
foreach (var conn in connections.Keys.ToArray())
{
CloseConnection(conn);
}
}
}
}
}