@@ -6,23 +6,29 @@ namespace Magic.IndexedDb.Factories
66{
77 public class MagicDbFactory : IMagicDbFactory , IAsyncDisposable
88 {
9- readonly Task < IJSObjectReference > _jsRuntime ;
9+ Lazy < Task < IJSObjectReference > > ? _jsRuntime ;
1010 readonly IServiceProvider _serviceProvider ;
11- readonly IDictionary < string , IndexedDbManager > _databases = new Dictionary < string , IndexedDbManager > ( ) ;
11+ readonly Dictionary < string , IndexedDbManager > _databases = new ( ) ;
1212
1313 public MagicDbFactory ( IServiceProvider serviceProvider , IJSRuntime jSRuntime )
1414 {
1515 _serviceProvider = serviceProvider ;
16- this . _jsRuntime = jSRuntime . InvokeAsync < IJSObjectReference > (
16+ this . _jsRuntime = new ( ( ) => jSRuntime . InvokeAsync < IJSObjectReference > (
1717 "import" ,
18- "./_content/Magic.IndexedDb/magicDB.js" ) . AsTask ( ) ;
18+ "./_content/Magic.IndexedDb/magicDB.js" ) . AsTask ( ) ) ;
1919 }
2020 public async ValueTask DisposeAsync ( )
2121 {
22- IJSObjectReference js ;
22+ var js = _jsRuntime ;
23+ _jsRuntime = null ;
24+
25+ if ( js is null || ! js . IsValueCreated )
26+ return ;
27+
28+ IJSObjectReference module ;
2329 try
2430 {
25- js = await _jsRuntime ;
31+ module = await js . Value ;
2632 }
2733 catch
2834 {
@@ -32,30 +38,33 @@ public async ValueTask DisposeAsync()
3238 try
3339 {
3440 var timeout = new CancellationTokenSource ( TimeSpan . FromSeconds ( 10 ) ) ;
35- await js . InvokeVoidAsync ( IndexedDbFunctions . CLOSE_ALL , timeout . Token ) ;
41+ await module . InvokeVoidAsync ( IndexedDbFunctions . CLOSE_ALL , timeout . Token ) ;
3642 }
37- catch
43+ finally
3844 {
39- // do nothing here
45+ await module . DisposeAsync ( ) ;
4046 }
41- await js . DisposeAsync ( ) ;
4247 }
4348
4449 public async ValueTask < IndexedDbManager > OpenAsync (
4550 DbStore dbStore , bool force = false ,
4651 CancellationToken cancellationToken = default )
4752 {
53+ ObjectDisposedException . ThrowIf ( _jsRuntime is null , this ) ;
54+
4855 if ( force || ! _databases . ContainsKey ( dbStore . Name ) )
4956 {
5057 var db = await IndexedDbManager . CreateAndOpenAsync (
51- dbStore , await _jsRuntime , cancellationToken ) ;
58+ dbStore , await _jsRuntime . Value , cancellationToken ) ;
5259 _databases [ dbStore . Name ] = db ;
5360 }
5461 return _databases [ dbStore . Name ] ;
5562 }
5663
5764 public IndexedDbManager Get ( string dbName )
5865 {
66+ ObjectDisposedException . ThrowIf ( _jsRuntime is null , this ) ;
67+
5968 if ( _databases . TryGetValue ( dbName , out var db ) )
6069 return db ;
6170 throw new MagicException (
0 commit comments