11using System ;
22using System . Collections . Generic ;
33using System . Data . Common ;
4+ using System . Diagnostics ;
45using System . Text ;
6+ using System . Threading ;
57using System . Threading . Tasks ;
68
79namespace SubSonic . Infrastructure
@@ -10,23 +12,32 @@ public class SharedDbConnectionScope
1012 : IConnectionScope
1113 , IDisposable
1214 {
13- [ ThreadStatic ]
14- private static Stack < SharedDbConnectionScope > __instances ;
15+ // [ThreadStatic]
16+ private static Dictionary < int , Stack < SharedDbConnectionScope > > __db_instances ;
1517
1618 private readonly DbDatabase dbDatabase ;
1719
1820 public SharedDbConnectionScope ( DbDatabase dbDatabase )
1921 {
2022 this . dbDatabase = dbDatabase ?? throw new ArgumentNullException ( nameof ( dbDatabase ) ) ;
2123 this . dbDatabase . InitializeSharedConnection ( ) ;
24+ this . threadId = Thread . CurrentThread . ManagedThreadId ;
2225
23- if ( __instances == null )
26+ if ( __db_instances == null )
2427 {
25- __instances = new Stack < SharedDbConnectionScope > ( ) ;
28+ __db_instances = new Dictionary < int , Stack < SharedDbConnectionScope > > ( ) ;
2629 }
27- __instances . Push ( this ) ;
30+
31+ if ( ! __db_instances . ContainsKey ( threadId ) )
32+ {
33+ __db_instances [ threadId ] = new Stack < SharedDbConnectionScope > ( ) ;
34+ }
35+
36+ __db_instances [ threadId ] . Push ( this ) ;
2837 }
2938
39+ private readonly int threadId ;
40+
3041 public DbConnection Connection => dbDatabase . CurrentSharedConnection ;
3142
3243 public DbDatabase Database => dbDatabase ;
@@ -41,11 +52,18 @@ protected virtual void Dispose(bool disposing)
4152 {
4253 if ( disposing )
4354 {
44- __instances ? . Pop ( ) ;
55+ SharedDbConnectionScope scope = __db_instances [ threadId ] . Pop ( ) ;
56+
57+ Debug . Assert ( scope . dbDatabase . CurrentSharedConnection . State == System . Data . ConnectionState . Closed , "open connection is being disposed." ) ;
58+
59+ if ( __db_instances [ threadId ] ? . Count == 0 )
60+ {
61+ __db_instances . Remove ( threadId ) ;
62+ }
4563
46- if ( __instances ? . Count == 0 )
64+ if ( __db_instances . Count == 0 )
4765 {
48- this . dbDatabase . ResetSharedConnection ( ) ;
66+ scope . dbDatabase . ResetSharedConnection ( ) ;
4967 }
5068
5169 disposedValue = true ;
0 commit comments