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

53 lines
1.5 KiB
C#
Raw Normal View History

2024-01-29 23:49:21 +00:00
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<ulong, RPGSession> _sessions;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
public SessionManager(IServiceProvider serviceProvider, ILogger<SessionManager> logger)
{
_sessions = [];
_serviceProvider = serviceProvider;
_logger = logger;
}
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);
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)
{
if (_sessions.TryRemove(session.SessionId, out _))
{
session.Dispose();
_logger.LogInformation("Session with id {id} was unregistered", session.SessionId);
}
}
}