hermes-common-library/Abstract/HandlerTypeManager.cs

59 lines
1.7 KiB
C#
Raw Permalink Normal View History

2024-06-24 18:28:40 -04:00
using Serilog;
namespace CommonSocketLibrary.Abstract
{
public interface ICodedOperation
{
int OperationCode { get; }
}
public interface IMessageTypeManager
{
Type? GetMessageTypeByCode(int code);
}
public abstract class MessageTypeManager<Handler> : IMessageTypeManager where Handler : ICodedOperation
2024-06-24 18:28:40 -04:00
{
private readonly IDictionary<int, Type> _types;
protected readonly ILogger _logger;
public MessageTypeManager(IEnumerable<Handler> handlers, ILogger logger)
2024-06-24 18:28:40 -04:00
{
_types = new Dictionary<int, Type>();
_logger = logger;
GenerateHandlerTypes(handlers);
2024-06-24 18:28:40 -04:00
}
public Type? GetMessageTypeByCode(int code)
{
_types.TryGetValue(code, out Type? type);
return type;
}
2024-06-24 18:28:40 -04:00
private void GenerateHandlerTypes(IEnumerable<Handler> handlers)
2024-06-24 18:28:40 -04:00
{
foreach (var handler in handlers)
2024-06-24 18:28:40 -04:00
{
if (handler == null)
2024-06-24 18:28:40 -04:00
{
_logger.Error($"Failed to link websocket handler due to null value.");
2024-06-24 18:28:40 -04:00
continue;
}
var type = handler.GetType();
2024-06-24 18:28:40 -04:00
var target = FetchMessageType(type);
if (target == null)
{
_logger.Error($"Failed to link websocket handler #{handler.OperationCode} due to no match for {target}.");
2024-06-24 18:28:40 -04:00
continue;
}
_types.Add(handler.OperationCode, target);
_logger.Debug($"Linked websocket handler #{handler.OperationCode} to type {target.AssemblyQualifiedName}.");
2024-06-24 18:28:40 -04:00
}
}
protected abstract Type? FetchMessageType(Type handlerType);
}
}