-
Notifications
You must be signed in to change notification settings - Fork 22
/
ManualTaskScenario.cs
93 lines (79 loc) · 2.77 KB
/
ManualTaskScenario.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
/*
$v=true
$p=4
$d=Manually started tasks
$h=By default, tasks are started automatically when they are injected. But you can override this behavior as shown in the example below. It is also recommended to add a binding for <c>CancellationToken</c> to be able to cancel the execution of a task.
$f=> [!IMPORTANT]
$f=> The method `Inject()`cannot be used outside of the binding setup.
*/
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable CheckNamespace
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable UnusedParameter.Global
namespace Pure.DI.UsageTests.BCL.ManualTaskScenario;
using Xunit;
// {
//# using Pure.DI;
// }
public class Scenario
{
[Fact]
public async Task Run()
{
// {
DI.Setup(nameof(Composition))
.Hint(Hint.Resolve, "Off")
// Overrides the default binding that performs an auto-start of a task
// when it is created. This binding will simply create the task.
// The start will be handled by the consumer.
.Bind<Task<TT>>().To(ctx =>
{
ctx.Inject(ctx.Tag, out Func<TT> factory);
ctx.Inject(out CancellationToken cancellationToken);
return new Task<TT>(factory, cancellationToken);
})
// Specifies to use CancellationToken from the composition root argument,
// if not specified then CancellationToken.None will be used
.RootArg<CancellationToken>("cancellationToken")
.Bind<IDependency>().To<Dependency>()
.Bind<IService>().To<Service>()
// Composition root
.Root<IService>("GetRoot");
var composition = new Composition();
using var cancellationTokenSource = new CancellationTokenSource();
// Creates a composition root with the CancellationToken passed to it
var service = composition.GetRoot(cancellationTokenSource.Token);
await service.RunAsync(cancellationTokenSource.Token);
// }
composition.SaveClassDiagram();
}
}
// {
interface IDependency
{
ValueTask DoSomething(CancellationToken cancellationToken);
}
class Dependency : IDependency
{
public ValueTask DoSomething(CancellationToken cancellationToken) => ValueTask.CompletedTask;
}
interface IService
{
Task RunAsync(CancellationToken cancellationToken);
}
class Service : IService
{
private readonly Task<IDependency> _dependencyTask;
public Service(Task<IDependency> dependencyTask)
{
_dependencyTask = dependencyTask;
// This is where the task starts
_dependencyTask.Start();
}
public async Task RunAsync(CancellationToken cancellationToken)
{
var dependency = await _dependencyTask;
await dependency.DoSomething(cancellationToken);
}
}
// }