-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
104 lines (77 loc) · 2.73 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
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
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace dotnet_core_console_di
{
class Program
{
static void Main(string[] args)
{
// dotnet add package Microsoft.Extensions.DependencyInjection
IServiceCollection services = new ServiceCollection();
ConfigureServices(services);
// services.AddScoped<IFooService, FooService>();
// services.AddScoped<IBooService, BooService>();
// services.AddLogging(configure => configure.AddConsole());
using(var serviceProvider = services.BuildServiceProvider())
{
IFooService fooService = serviceProvider.GetService<IFooService>();
string result = fooService.Get();
System.Console.WriteLine(result);
IBooService booService = serviceProvider.GetService<IBooService>();
booService.DoWork();
}
System.Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IFooService, FooService>();
services.AddScoped<IBooService, BooService>();
services.AddLogging(configure => configure.AddConsole());
services.AddOptions();
services.Configure<BooOptions>(options =>
{
options.Count = 5;
});
}
}
public interface IFooService
{
string Get();
}
public interface IBooService
{
void DoWork();
}
public class FooService : IFooService
{
public string Get() => "Boo";
}
public class BooOptions
{
public byte Count { get; set; }
}
public class BooService : IBooService
{
private readonly IFooService fooService;
// dotnet add package Microsoft.Extensions.Logging.Console
private readonly ILogger logger;
private readonly BooOptions options;
public BooService(IOptions<BooOptions> options, IFooService fooService, ILogger<BooService> logger)
{
this.options = options.Value;
this.fooService = fooService;
this.logger = logger;
}
public void DoWork()
{
for(byte i = 0; i<options.Count; i++)
{
System.Console.WriteLine(fooService.Get());
logger.LogInformation(fooService.Get());
}
}
}
}