-
Notifications
You must be signed in to change notification settings - Fork 22
/
AsyncDisposableScopeScenario.cs
108 lines (88 loc) · 2.66 KB
/
AsyncDisposableScopeScenario.cs
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
$v=true
$p=9
$d=Async disposable scope
*/
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable CheckNamespace
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable UnusedMember.Local
// ReSharper disable ArrangeTypeMemberModifiers
#pragma warning disable CS9113 // Parameter is unread.
namespace Pure.DI.UsageTests.Lifetimes.AsyncDisposableScopeScenario;
using Xunit;
using static Lifetime;
// {
interface IDependency
{
bool IsDisposed { get; }
}
class Dependency : IDependency, IAsyncDisposable
{
public bool IsDisposed { get; private set; }
public ValueTask DisposeAsync()
{
IsDisposed = true;
return ValueTask.CompletedTask;
}
}
interface IService
{
IDependency Dependency { get; }
}
class Service(IDependency dependency) : IService
{
public IDependency Dependency => dependency;
}
// Implements a session
class Session(Composition composition) : Composition(composition);
class Program(Func<Session> sessionFactory)
{
public Session CreateSession() => sessionFactory();
}
partial class Composition
{
static void Setup() =>
DI.Setup()
// This hint indicates to not generate methods such as Resolve
.Hint(Hint.Resolve, "Off")
.Bind().As(Scoped).To<Dependency>()
.Bind().To<Service>()
// Session composition root
.Root<IService>("SessionRoot")
// Program composition root
.Root<Program>("ProgramRoot");
}
// }
public class Scenario
{
[Fact]
public async Task Run()
{
// {
var composition = new Composition();
var program = composition.ProgramRoot;
// Creates session #1
var session1 = program.CreateSession();
var dependency1 = session1.SessionRoot.Dependency;
var dependency12 = session1.SessionRoot.Dependency;
// Checks the identity of scoped instances in the same session
dependency1.ShouldBe(dependency12);
// Creates session #2
var session2 = program.CreateSession();
var dependency2 = session2.SessionRoot.Dependency;
// Checks that the scoped instances are not identical in different sessions
dependency1.ShouldNotBe(dependency2);
// Disposes of session #1
await session1.DisposeAsync();
// Checks that the scoped instance is finalized
dependency1.IsDisposed.ShouldBeTrue();
// Disposes of session #2
await session2.DisposeAsync();
// Checks that the scoped instance is finalized
dependency2.IsDisposed.ShouldBeTrue();
// }
composition.SaveClassDiagram();
}
}