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