-
Notifications
You must be signed in to change notification settings - Fork 22
/
ScopeScenario.cs
105 lines (85 loc) · 2.63 KB
/
ScopeScenario.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
/*
$v=true
$p=4
$d=Scope
$h=The _Scoped_ lifetime ensures that there will be a single instance of the dependency for each 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.ScopeScenario;
using Xunit;
using static Lifetime;
// {
interface IDependency
{
bool IsDisposed { get; }
}
class Dependency : IDependency, IDisposable
{
public bool IsDisposed { get; private set; }
public void Dispose() => IsDisposed = true;
}
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 void 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
session1.Dispose();
// Checks that the scoped instance is finalized
dependency1.IsDisposed.ShouldBeTrue();
// Disposes of session #2
session2.Dispose();
// Checks that the scoped instance is finalized
dependency2.IsDisposed.ShouldBeTrue();
// }
composition.SaveClassDiagram();
}
}