@@ -6,23 +6,29 @@ namespace Magic.IndexedDb.Factories
6
6
{
7
7
public class MagicDbFactory : IMagicDbFactory , IAsyncDisposable
8
8
{
9
- readonly Task < IJSObjectReference > _jsRuntime ;
9
+ Lazy < Task < IJSObjectReference > > ? _jsRuntime ;
10
10
readonly IServiceProvider _serviceProvider ;
11
- readonly IDictionary < string , IndexedDbManager > _databases = new Dictionary < string , IndexedDbManager > ( ) ;
11
+ readonly Dictionary < string , IndexedDbManager > _databases = new ( ) ;
12
12
13
13
public MagicDbFactory ( IServiceProvider serviceProvider , IJSRuntime jSRuntime )
14
14
{
15
15
_serviceProvider = serviceProvider ;
16
- this . _jsRuntime = jSRuntime . InvokeAsync < IJSObjectReference > (
16
+ this . _jsRuntime = new ( ( ) => jSRuntime . InvokeAsync < IJSObjectReference > (
17
17
"import" ,
18
- "./_content/Magic.IndexedDb/magicDB.js" ) . AsTask ( ) ;
18
+ "./_content/Magic.IndexedDb/magicDB.js" ) . AsTask ( ) ) ;
19
19
}
20
20
public async ValueTask DisposeAsync ( )
21
21
{
22
- IJSObjectReference js ;
22
+ var js = _jsRuntime ;
23
+ _jsRuntime = null ;
24
+
25
+ if ( js is null || ! js . IsValueCreated )
26
+ return ;
27
+
28
+ IJSObjectReference module ;
23
29
try
24
30
{
25
- js = await _jsRuntime ;
31
+ module = await js . Value ;
26
32
}
27
33
catch
28
34
{
@@ -32,30 +38,33 @@ public async ValueTask DisposeAsync()
32
38
try
33
39
{
34
40
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 ) ;
36
42
}
37
- catch
43
+ finally
38
44
{
39
- // do nothing here
45
+ await module . DisposeAsync ( ) ;
40
46
}
41
- await js . DisposeAsync ( ) ;
42
47
}
43
48
44
49
public async ValueTask < IndexedDbManager > OpenAsync (
45
50
DbStore dbStore , bool force = false ,
46
51
CancellationToken cancellationToken = default )
47
52
{
53
+ ObjectDisposedException . ThrowIf ( _jsRuntime is null , this ) ;
54
+
48
55
if ( force || ! _databases . ContainsKey ( dbStore . Name ) )
49
56
{
50
57
var db = await IndexedDbManager . CreateAndOpenAsync (
51
- dbStore , await _jsRuntime , cancellationToken ) ;
58
+ dbStore , await _jsRuntime . Value , cancellationToken ) ;
52
59
_databases [ dbStore . Name ] = db ;
53
60
}
54
61
return _databases [ dbStore . Name ] ;
55
62
}
56
63
57
64
public IndexedDbManager Get ( string dbName )
58
65
{
66
+ ObjectDisposedException . ThrowIf ( _jsRuntime is null , this ) ;
67
+
59
68
if ( _databases . TryGetValue ( dbName , out var db ) )
60
69
return db ;
61
70
throw new MagicException (
0 commit comments