add better initialization

This commit is contained in:
Pilzinsel64
2025-10-09 07:26:42 +02:00
parent 5e035b43df
commit ccb9f8350e
7 changed files with 40 additions and 10 deletions

View File

@@ -17,6 +17,7 @@ public class ApiServer : IApiServer
public class MissingDataManagerException : Exception { }
protected readonly List<PrivateMessageHandler> handlers = [];
protected readonly List<object> handlerObjects = [];
protected readonly Dictionary<Type, IApiMessageSerializer> serializers = [];
protected readonly Dictionary<ThreadHolder, IDataManager> managers = [];
protected HttpListener httpListener;
@@ -25,6 +26,7 @@ public class ApiServer : IApiServer
protected SemaphoreSlim? semaphore;
protected bool doListen;
protected bool isAutoRestarting;
protected bool initializedHandlers;
public event OnCheckAuthenticationEventHandler? OnCheckAuthentication;
public event OnCheckContextEventHandler? OnCheckContext;
@@ -109,6 +111,7 @@ public class ApiServer : IApiServer
public virtual void Start()
{
Log.Info("Starting listener");
InitializeHandlers();
httpListener.Prefixes.Add(ApiUrl + "/");
doListen = true;
httpListener.Start();
@@ -183,6 +186,20 @@ public class ApiServer : IApiServer
semaphore.Release();
}
protected virtual void InitializeHandlers()
{
foreach (var instance in handlerObjects)
{
if (instance is IApiHandlerInitializer initializer)
initializer.Initialize();
}
}
public virtual T? GetHandler<T>()
{
return handlerObjects.OfType<T>().FirstOrDefault();
}
public virtual Dictionary<string, string[]> GetEndpoints()
{
return handlers.OrderBy(n => n.Attribute.Route).GroupBy(n => n.Attribute.Route).ToDictionary(n => n.Key, n => n.SelectMany(n => n.Attribute.Methods.OrderBy(n => n)).ToArray());
@@ -190,9 +207,8 @@ public class ApiServer : IApiServer
public virtual void RegisterHandler<T>(T instance) where T : class
{
// Initialize
if (instance is IApiHandlerInitializer initializer)
initializer.Initialize(this);
if (!handlerObjects.Contains(instance))
handlerObjects.Add(instance);
// Get all public instance methods
var methods = instance.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public);