-
Notifications
You must be signed in to change notification settings - Fork 22
/
CheckForRootScenario.cs
83 lines (68 loc) · 2.16 KB
/
CheckForRootScenario.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
/*
$v=true
$p=7
$d=Check for a root
$h=Sometimes you need to check if you can get the root of a composition using the _Resolve_ method before calling it, this example will show you how to do it:
$f=For more hints, see [this](README.md#setup-hints) page.
*/
// ReSharper disable CheckNamespace
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedTypeParameter
// ReSharper disable UnusedParameterInPartialMethod
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable UnusedMemberInSuper.Global
// ReSharper disable ArrangeTypeMemberModifiers
namespace Pure.DI.UsageTests.Hints.CheckForRootScenario;
using Shouldly;
using Xunit;
// {
interface IDependency;
class Dependency : IDependency;
interface IService
{
IDependency Dependency { get; }
}
class Service : IService
{
[Tag("MyDep")]
public required IDependency Dependency { get; init; }
}
partial class Composition
{
private static readonly HashSet<(Type type, object? tag)> Roots = [];
// Check that the root can be resolved by Resolve methods
internal static bool HasRoot(Type type, object? key = default) =>
Roots.Contains((type, key));
static void Setup() =>
DI.Setup()
// Specifies to use the partial OnNewRoot method
// to register each root
.Hint(Hint.OnNewRoot, "On")
.Bind("MyDep").To<Dependency>()
.Bind().To<Service>()
// Composition roots
.Root<IDependency>(tag: "MyDep")
.Root<IService>("Root");
// Adds a new root to the hash set
private static partial void OnNewRoot<TContract, T>(
IResolver<Composition, TContract> resolver,
string name,
object? tag,
Lifetime lifetime) =>
Roots.Add((typeof(TContract), tag));
}
// }
public class Scenario
{
[Fact]
public void Run()
{
// {
Composition.HasRoot(typeof(IService)).ShouldBeTrue();
Composition.HasRoot(typeof(IDependency), "MyDep").ShouldBeTrue();
Composition.HasRoot(typeof(IDependency)).ShouldBeFalse();
Composition.HasRoot(typeof(IComparable)).ShouldBeFalse();
// }
new Composition().SaveClassDiagram();
}
}