forked from SciSharp/BotSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHookEmitter.cs
More file actions
69 lines (60 loc) · 2.07 KB
/
HookEmitter.cs
File metadata and controls
69 lines (60 loc) · 2.07 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
59
60
61
62
63
64
65
66
67
68
69
using BotSharp.Abstraction.Hooks;
using BotSharp.Abstraction.Infrastructures;
namespace BotSharp.Core.Infrastructures;
public static class HookEmitter
{
public static HookEmittedResult Emit<T>(IServiceProvider services, Action<T> action, string agentId, HookEmitOption<T>? option = null) where T : IHookBase
{
var logger = services.GetRequiredService<ILogger<T>>();
var result = new HookEmittedResult();
var hooks = services.GetHooks<T>(agentId);
option = option ?? new();
foreach (var hook in hooks)
{
try
{
if (option.ShouldExecute == null || option.ShouldExecute(hook))
{
logger.LogDebug($"Emit hook action on {action.Method.Name}({hook.GetType().Name})");
action(hook);
if (option.OnlyOnce)
{
break;
}
}
}
catch (Exception ex)
{
logger.LogError(ex.ToString());
}
}
return result;
}
public static async Task<HookEmittedResult> Emit<T>(IServiceProvider services, Func<T, Task> action, string agentId, HookEmitOption<T>? option = null) where T : IHookBase
{
var logger = services.GetRequiredService<ILogger<T>>();
var result = new HookEmittedResult();
var hooks = services.GetHooks<T>(agentId);
option = option ?? new();
foreach (var hook in hooks)
{
try
{
if (option.ShouldExecute == null || option.ShouldExecute(hook))
{
logger.LogDebug($"Emit hook action on {action.Method.Name}({hook.GetType().Name})");
await action(hook);
if (option.OnlyOnce)
{
break;
}
}
}
catch (Exception ex)
{
logger.LogError(ex.ToString());
}
}
return result;
}
}