Snowflake/RPG.Services.Core/Session/SessionManager.cs

53 lines
1.5 KiB
C#
Raw Permalink Normal View History

2024-01-18 22:13:40 +00:00
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2024-01-18 22:13:40 +00:00
namespace RPG.Services.Core.Session;
public class SessionManager
{
private readonly ConcurrentDictionary<ulong, RPGSession> _sessions;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
2024-01-18 22:13:40 +00:00
public SessionManager(IServiceProvider serviceProvider, ILogger<SessionManager> logger)
2024-01-18 22:13:40 +00:00
{
_sessions = [];
_serviceProvider = serviceProvider;
_logger = logger;
2024-01-18 22:13:40 +00:00
}
public TSession? Create<TSession>(ulong id) where TSession : RPGSession
{
if (_sessions.ContainsKey(id)) return null;
TSession session = ActivatorUtilities.CreateInstance<TSession>(_serviceProvider, id);
_sessions[id] = session;
_logger.LogInformation("New session (id={id}) registered", id);
2024-01-18 22:13:40 +00:00
return session;
}
public bool TryGet<TSession>(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)
{
2024-01-19 14:45:18 +00:00
if (_sessions.TryRemove(session.SessionId, out _))
{
session.Dispose();
_logger.LogInformation("Session with id {id} was unregistered", session.SessionId);
2024-01-19 14:45:18 +00:00
}
2024-01-18 22:13:40 +00:00
}
}