forked from mayuki/Cocona
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
94 lines (85 loc) · 2.84 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
using System;
using System.Threading.Tasks;
using Cocona;
using Cocona.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace CoconaSample.InAction.CommandFilter
{
[SampleCommandFilter("Class")]
class Program
{
static void Main(string[] args)
{
CoconaApp.Run<Program>(args);
}
// Example:
// [SampleCommandFilter(Class)]
// [SampleCommandFilter(Method)]
// [SampleCommandFilterWithDI]
// Hello (Command)
[SampleCommandFilter("Method")]
[SampleCommandFilterWithDI]
public void Hello()
{
Console.WriteLine($"Hello Konnichiwa");
}
}
class SampleCommandFilterAttribute : CommandFilterAttribute
{
private readonly string _label;
public SampleCommandFilterAttribute(string label)
{
_label = label;
}
public override async ValueTask<int> OnCommandExecutionAsync(CoconaCommandExecutingContext ctx, CommandExecutionDelegate next)
{
Console.WriteLine($"[SampleCommandFilter({_label})] Before Command: {ctx.Command.Name}");
try
{
return await next(ctx);
}
catch (Exception ex)
{
Console.WriteLine($"[SampleCommandFilter({_label})] Exception: {ex.GetType().FullName}: {ex.Message}");
throw;
}
finally
{
Console.WriteLine($"[SampleCommandFilter({_label})] End Command: {ctx.Command.Name}");
}
}
}
class SampleCommandFilterWithDIAttribute : Attribute, IFilterFactory
{
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
return ActivatorUtilities.CreateInstance<SampleCommandFilterWithDI>(serviceProvider);
}
}
class SampleCommandFilterWithDI : ICommandFilter
{
private readonly ILogger _logger;
public SampleCommandFilterWithDI(ILogger<SampleCommandFilterWithDI> logger)
{
_logger = logger;
}
public async ValueTask<int> OnCommandExecutionAsync(CoconaCommandExecutingContext ctx, CommandExecutionDelegate next)
{
_logger.LogInformation($"[SampleCommandFilterWithDI] Before Command: {ctx.Command.Name}");
try
{
return await next(ctx);
}
catch (Exception ex)
{
_logger.LogInformation($"[SampleCommandFilterWithDI] Exception: {ex.GetType().FullName}: {ex.Message}");
throw;
}
finally
{
_logger.LogInformation($"[SampleCommandFilterWithDI] End Command: {ctx.Command.Name}");
}
}
}
}