-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsoleUIService.cs
93 lines (78 loc) · 2.91 KB
/
ConsoleUIService.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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CommandsAndHandlers.Commands;
using CommandsAndHandlers.Dispatcher;
using Microsoft.Extensions.Hosting;
namespace CommandsAndHandlers
{
public class ConsoleUIService : IHostedService
{
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly ICommandDispatcher _commandDispatcher;
private readonly Dictionary<string, Type> _commandsDictionary;
public ConsoleUIService(
IHostApplicationLifetime applicationLifetime,
ICommandDispatcher commandDispatcher,
Dictionary<string, Type> commandsDictionary
)
{
_applicationLifetime = applicationLifetime;
_commandDispatcher = commandDispatcher;
_commandsDictionary = commandsDictionary;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_applicationLifetime.ApplicationStarted.Register(OnStarted);
_applicationLifetime.ApplicationStopping.Register(OnStopping);
_applicationLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
Console.WriteLine("-----------------------------");
Console.WriteLine("Application stared!");
Console.WriteLine("Press 'Ctrl + C' to stop application");
Console.WriteLine("-----------------------------\n\n\n\n");
StartCommandLineObserving();
}
private void OnStopping()
{
Console.WriteLine("\n\n\n\nApplication is stopping...\n\n\n\n");
}
private void OnStopped()
{
Console.WriteLine("-----------------------------");
Console.WriteLine("Application stopped!");
Console.WriteLine("-----------------------------");
}
private void StartCommandLineObserving()
{
string commandExecuteName;
while(true)
{
Console.Write("\nEnter the command: ");
commandExecuteName = Console.ReadLine();
if (_commandsDictionary.TryGetValue(commandExecuteName, out Type command))
{
var commandToExecute = Activator.CreateInstance(command, _commandDispatcher) as Command;
commandToExecute?.Execute();
}
else if (commandExecuteName != "exit")
{
Console.WriteLine($"No command with name {commandExecuteName} was found!");
}
else
{
break;
}
}
Environment.Exit(-1);
}
}
}