1+ using System . Collections ;
2+ using System . Threading ;
3+ using NHibernate . Cfg ;
4+ using NHibernate . Context ;
5+ using NHibernate . Engine ;
6+ using NUnit . Framework ;
7+
8+ namespace NHibernate . Test . ConnectionTest
9+ {
10+ [ TestFixture ]
11+ public class ThreadStaticSessionContextFixture : ConnectionManagementTestCase
12+ {
13+ protected override ISession GetSessionUnderTest ( )
14+ {
15+ var session = OpenSession ( ) ;
16+ session . BeginTransaction ( ) ;
17+ return session ;
18+ }
19+
20+ protected override void Configure ( Configuration configuration )
21+ {
22+ base . Configure ( cfg ) ;
23+ cfg . SetProperty ( Environment . CurrentSessionContextClass , "thread_static" ) ;
24+ }
25+
26+ [ Test ]
27+ public void ThreadStaticIsolation ( )
28+ {
29+ using ( var session1 = OpenSession ( ) )
30+ using ( var session2 = OpenSession ( ) )
31+ {
32+ var thread1 = new Thread ( ( ) =>
33+ {
34+ for ( var i = 1 ; i <= 100 ; i ++ )
35+ {
36+ CurrentSessionContext . Bind ( session1 ) ;
37+ Thread . Sleep ( 1 ) ;
38+ // Yes, NUnit catches asserts inside threads.
39+ AssertCurrentSession ( Sfi , session1 , $ "At iteration { i } , unexpected session for thread 1.") ;
40+ }
41+ } ) ;
42+
43+ var thread2 = new Thread ( ( ) =>
44+ {
45+ for ( var i = 1 ; i <= 34 ; i ++ )
46+ {
47+ CurrentSessionContext . Bind ( session2 ) ;
48+ // Have a different longer sleep for ensuring the other thread have changed its own.
49+ Thread . Sleep ( 3 ) ;
50+ AssertCurrentSession ( Sfi , session2 , $ "At iteration { i } , unexpected session for thread 2.") ;
51+ }
52+ } ) ;
53+
54+ thread1 . Start ( ) ;
55+ thread2 . Start ( ) ;
56+ thread1 . Join ( ) ;
57+ thread2 . Join ( ) ;
58+ }
59+ }
60+
61+ [ Test ]
62+ public void ThreadStaticMultiFactory ( )
63+ {
64+ using ( var factory1 = cfg . BuildSessionFactory ( ) )
65+ using ( var session1 = factory1 . OpenSession ( ) )
66+ using ( var factory2 = cfg . BuildSessionFactory ( ) )
67+ using ( var session2 = factory2 . OpenSession ( ) )
68+ {
69+ CurrentSessionContext . Bind ( session1 ) ;
70+ AssertCurrentSession ( factory1 , session1 , "Unexpected session for factory1 after bind of session1." ) ;
71+ CurrentSessionContext . Bind ( session2 ) ;
72+ AssertCurrentSession ( factory2 , session2 , "Unexpected session for factory2 after bind of session2." ) ;
73+ AssertCurrentSession ( factory1 , session1 , "Unexpected session for factory1 after bind of session2." ) ;
74+ }
75+ }
76+
77+ private void AssertCurrentSession ( ISessionFactory factory , ISession session , string message )
78+ {
79+ Assert . That (
80+ factory . GetCurrentSession ( ) ,
81+ Is . EqualTo ( session ) ,
82+ "{0} {1} instead of {2}." , message ,
83+ factory . GetCurrentSession ( ) . GetSessionImplementation ( ) . SessionId ,
84+ session . GetSessionImplementation ( ) . SessionId ) ;
85+ }
86+ }
87+ }
0 commit comments