diff --git a/src/Immediate.Cache.Shared/ApplicationCacheBase.cs b/src/Immediate.Cache.Shared/ApplicationCacheBase.cs index faf7edb..4cb109b 100644 --- a/src/Immediate.Cache.Shared/ApplicationCacheBase.cs +++ b/src/Immediate.Cache.Shared/ApplicationCacheBase.cs @@ -195,11 +195,11 @@ private async Task RunHandler(CancellationTokenSource tokenSource) try { var token = tokenSource.Token; - var scope = handler.GetScope(); + var scope = handler.GetScope(out var service); await using (scope.ConfigureAwait(false)) { - var response = await scope.Service + var response = await service .HandleAsync( request, token diff --git a/src/Immediate.Cache.Shared/Owned.cs b/src/Immediate.Cache.Shared/Owned.cs index 2cfc5a7..a2357d7 100644 --- a/src/Immediate.Cache.Shared/Owned.cs +++ b/src/Immediate.Cache.Shared/Owned.cs @@ -22,12 +22,30 @@ IServiceScopeFactory serviceScopeFactory /// An containing both the scope and the service, so that the scope can be disposed /// at the appropriate time. /// - public OwnedScope GetScope() + public OwnedScope GetScope() => GetScope(out _); + + /// + /// Creates a temporary scope and gets an instance of the service from that scope. + /// + /// + /// The instance of the service created from the scope. + /// + /// + /// An containing both the scope and the service, so that the scope can be disposed + /// at the appropriate time. + /// + public OwnedScope GetScope(out T service) { var scope = serviceScopeFactory.CreateAsyncScope(); - return new( - scope.ServiceProvider.GetRequiredService(), - scope - ); + try + { + service = scope.ServiceProvider.GetRequiredService(); + return new(service, scope); + } + catch + { + scope.Dispose(); + throw; + } } }