1+ using System ;
12using System . Collections . Generic ;
23using System . Runtime . CompilerServices ;
34
@@ -78,16 +79,40 @@ public static void RemoveInstance(string uid, string name, IDictionary<string, s
7879 }
7980
8081 /// <summary>
81- /// Returns a Named Instance of the SessionFactory from the local "cache" identified by name.
82+ /// Get an instance of the SessionFactory from the local "cache" identified by name if it
83+ /// exists, otherwise run the provided factory and return its result.
8284 /// </summary>
8385 /// <param name="name">The name of the ISessionFactory.</param>
86+ /// <param name="instanceFactory">The ISessionFactory factory to use if the instance is not
87+ /// found.</param>
8488 /// <returns>An instantiated ISessionFactory.</returns>
89+ /// <remarks>It is the caller responsibility to ensure <paramref name="instanceFactory"/>
90+ /// will add and yield a session factory of the requested <paramref name="name"/>.</remarks>
91+ [ MethodImpl ( MethodImplOptions . Synchronized ) ]
92+ public static ISessionFactory GetOrAddNamedInstance ( string name , Func < ISessionFactory > instanceFactory )
93+ {
94+ if ( instanceFactory == null )
95+ throw new ArgumentNullException ( nameof ( instanceFactory ) ) ;
96+
97+ if ( NamedInstances . TryGetValue ( name , out var factory ) )
98+ return factory ;
99+ return instanceFactory ( ) ;
100+ }
101+
102+ /// <summary>
103+ /// Returns a Named Instance of the SessionFactory from the local "cache" identified by name.
104+ /// </summary>
105+ /// <param name="name">The name of the ISessionFactory.</param>
106+ /// <returns>An ISessionFactory if found, <see langword="null" /> otherwise.</returns>
107+ /// <remarks>If the session factory instantiation is performed concurrently, this method
108+ /// may yield an instance of it still being built, which may lead to threading issues.
109+ /// Use <see cref="GetOrAddNamedInstance(string, Func{ISessionFactory})" /> instead in such case.</remarks>
85110 [ MethodImpl ( MethodImplOptions . Synchronized ) ]
86111 public static ISessionFactory GetNamedInstance ( string name )
87112 {
88113 log . Debug ( "lookup: name={0}" , name ) ;
89114 ISessionFactory factory ;
90- bool found = NamedInstances . TryGetValue ( name , out factory ) ;
115+ bool found = NamedInstances . TryGetValue ( name , out factory ) ;
91116 if ( ! found )
92117 {
93118 log . Warn ( "Not found: {0}" , name ) ;
@@ -99,7 +124,7 @@ public static ISessionFactory GetNamedInstance(string name)
99124 /// Returns an Instance of the SessionFactory from the local "cache" identified by UUID.
100125 /// </summary>
101126 /// <param name="uid">The identifier of the ISessionFactory.</param>
102- /// <returns>An instantiated ISessionFactory.</returns>
127+ /// <returns>An ISessionFactory if found, <see langword="null" /> otherwise .</returns>
103128 [ MethodImpl ( MethodImplOptions . Synchronized ) ]
104129 public static ISessionFactory GetInstance ( string uid )
105130 {
0 commit comments