-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathProgram.cs
More file actions
58 lines (49 loc) · 1.82 KB
/
Copy pathProgram.cs
File metadata and controls
58 lines (49 loc) · 1.82 KB
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
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection;
namespace KeyedServices
{
[Command(Name = "keyed-di", Description = "Keyed Dependency Injection sample project")]
[HelpOption]
class Program
{
public static int Main(string[] args)
{
var services = new ServiceCollection()
.AddKeyedSingleton<IGreeter, FormalGreeter>("formal")
.AddKeyedSingleton<IGreeter, CasualGreeter>("casual")
.AddSingleton<IConsole>(PhysicalConsole.Singleton)
.BuildServiceProvider();
var app = new CommandLineApplication<Program>();
app.Conventions.UseDefaultConventions()
.UseConstructorInjection(services);
return app.Execute(args);
}
[Option(Description = "The subject to greet")]
public string Subject { get; set; } = "world";
[Option(Description = "Use casual greeting")]
public bool Casual { get; set; }
private int OnExecute(
[FromKeyedServices("formal")] IGreeter formalGreeter,
[FromKeyedServices("casual")] IGreeter casualGreeter,
IConsole console)
{
var greeter = Casual ? casualGreeter : formalGreeter;
console.WriteLine(greeter.Greet(Subject));
return 0;
}
}
interface IGreeter
{
string Greet(string subject);
}
class FormalGreeter : IGreeter
{
public string Greet(string subject) => $"Good day, {subject}. How do you do?";
}
class CasualGreeter : IGreeter
{
public string Greet(string subject) => $"Hey {subject}!";
}
}