using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace RPG.Services.Core.Session; public class SessionManager { private readonly ConcurrentDictionary _sessions; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public SessionManager(IServiceProvider serviceProvider, ILogger logger) { _sessions = []; _serviceProvider = serviceProvider; _logger = logger; } public TSession? Create(ulong id) where TSession : RPGSession { if (_sessions.ContainsKey(id)) return null; TSession session = ActivatorUtilities.CreateInstance(_serviceProvider, id); _sessions[id] = session; _logger.LogInformation("New session (id={id}) registered", id); return session; } public bool TryGet(ulong id, [NotNullWhen(true)] out TSession? session) where TSession : RPGSession { if (_sessions.TryGetValue(id, out RPGSession? value)) { session = (TSession)value; return true; } session = null; return false; } public void Remove(RPGSession session) { if (_sessions.TryRemove(session.SessionId, out _)) { session.Dispose(); _logger.LogInformation("Session with id {id} was unregistered", session.SessionId); } } }