-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
81 lines (69 loc) · 2.53 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
using TodoParser.Parsing;
using Sprache;
using System;
using Microsoft.Extensions.DependencyInjection;
using TodoParser.Handlers;
namespace TodoParser
{
public static class Program
{
const string PROMPT = "> ";
private static void Main()
{
// Set up the DependencyInjection collection and provider
var services = ConfigureServices();
var provider = services.BuildServiceProvider();
var parser = CommandGrammar.Source;
string line;
do
{
Console.Write(PROMPT);
line = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(line))
{
try
{
var result = parser.Parse(line);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(result);
Console.ResetColor();
HandleCommand(provider, result);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
Console.ResetColor();
Console.WriteLine();
}
}
while (line != null);
}
private static IServiceCollection ConfigureServices()
{
var services = new ServiceCollection();
services.AddTransient<IHandler<ReadCommand>, ReadHandler>();
services.AddTransient<IHandler<DeleteCommand>, DeleteHandler>();
services.AddTransient<IHandler<NextCommand>, NextHandler>();
return services;
}
private static void HandleCommand(ServiceProvider provider, Command command)
{
switch (command)
{
case ReadCommand read:
provider.GetRequiredService<IHandler<ReadCommand>>().Run(read);
break;
case DeleteCommand delete:
provider.GetRequiredService<IHandler<DeleteCommand>>().Run(delete);
break;
case NextCommand next:
provider.GetRequiredService<IHandler<NextCommand>>().Run(next);
break;
default:
throw new Exception($"Unknown command type {command.GetType().FullName} sent to HandleCommand!");
}
}
}
}