-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOwned.cs
More file actions
43 lines (40 loc) · 1.46 KB
/
Owned.cs
File metadata and controls
43 lines (40 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using Microsoft.Extensions.DependencyInjection;
namespace Immediate.Cache;
/// <summary>
/// A factory for creating a scope containing a strong-type service as it's root.
/// </summary>
/// <typeparam name="T">
/// The type of the service that should be created at the root of the scope.
/// </typeparam>
/// <param name="serviceScopeFactory">
/// A <see cref="IServiceScopeFactory"/> used to create the scope for the service.
/// </param>
public sealed class Owned<T>(
IServiceScopeFactory serviceScopeFactory
) where T : class
{
/// <summary>
/// Creates a temporary scope and gets an instance of the service from that scope.
/// </summary>
/// <returns>
/// An <see cref="OwnedScope{T}"/> containing both the scope and the service, so that the scope can be disposed
/// at the appropriate time.
/// </returns>
public OwnedScope<T> GetScope() => GetScope(out _);
/// <summary>
/// Creates a temporary scope and gets an instance of the service from that scope.
/// </summary>
/// <param name="service">
/// The instance of the service created from the scope.
/// </param>
/// <returns>
/// An <see cref="OwnedScope{T}"/> containing both the scope and the service, so that the scope can be disposed
/// at the appropriate time.
/// </returns>
public OwnedScope<T> GetScope(out T service)
{
var scope = serviceScopeFactory.CreateAsyncScope();
service = scope.ServiceProvider.GetRequiredService<T>();
return new(service, scope);
}
}