-
Notifications
You must be signed in to change notification settings - Fork 22
/
Program.cs
74 lines (59 loc) · 2.02 KB
/
Program.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
using Pure.DI;
using static Pure.DI.Lifetime;
// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedMemberInSuper.Global
namespace Sample;
using System.Diagnostics;
// Let's create an abstraction
public interface IBox<out T>
{
T Content { get; }
}
public interface ICat
{
State State { get; }
}
public enum State
{
Alive,
Dead
}
// Here is our implementation
public record CardboardBox<T>(T Content) : IBox<T>;
public class ShroedingersCat(Lazy<State> superposition): ICat
{
// The decoherence of the superposition
// at the time of observation via an irreversible process
public State State => superposition.Value;
public override string ToString() => $"{State} cat";
}
// Let's glue all together
internal partial class Composition
{
// In fact, this code is never run, and the method can have any name or be a constructor, for example,
// and can be in any part of the compiled code because this is just a hint to set up an object graph.
// [Conditional("DI")] attribute avoids generating IL code for the method that follows it.
// Since this method is needed only at the compile time.
[Conditional("DI")]
static void Setup() => DI.Setup()
// Models a random subatomic event that may or may not occur
.Bind().As(Singleton).To<Random>()
// Quantum superposition of two states: Alive or Dead
.Bind().To((Random random) => (State)random.Next(2))
.Bind().To<ShroedingersCat>()
// Cardboard box with any contents
.Bind().To<CardboardBox<TT>>()
// Provides the composition root
.Root<Program>("Root");
}
// Time to open boxes!
public class Program(IBox<ICat> box)
{
// Composition Root, a single place in an application
// where the composition of the object graphs
// for an application take place
public static void Main() => new Composition().Root.Run();
private void Run() => Console.WriteLine(box);
}