Files
Ayay/SHH.CameraService/Core/CmdClients/CommandDispatcher.cs

46 lines
1.4 KiB
C#
Raw Normal View History

using Newtonsoft.Json.Linq;
namespace SHH.CameraService;
public class CommandDispatcher
{
// 路由表Key = ActionName, Value = Handler
private readonly Dictionary<string, ICommandHandler> _handlers;
// 通过依赖注入拿到所有实现了 ICommandHandler 的类
public CommandDispatcher(IEnumerable<ICommandHandler> handlers)
{
_handlers = handlers.ToDictionary(h => h.ActionName, h => h);
}
public async Task DispatchAsync(string jsonMessage)
{
try
{
var jObj = JObject.Parse(jsonMessage);
string action = jObj["Action"]?.ToString();
var payload = jObj["Payload"];
if (string.IsNullOrEmpty(action)) return;
// 1. 查找是否有对应的处理器
if (_handlers.TryGetValue(action, out var handler))
{
await handler.ExecuteAsync(payload);
}
else if (action == "ACK")
{
// ACK 是特殊的,可以直接在这里处理或者忽略
Console.WriteLine($"[指令] 握手成功: {jObj["Message"]}");
}
else
{
Console.WriteLine($"[警告] 未知的指令: {action}");
}
}
catch (Exception ex)
{
Console.WriteLine($"[分发错误] {ex.Message}");
}
}
}