2024-01-18 22:13:40 +00:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2024-01-19 22:39:12 +00:00
|
|
|
|
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;
|
2024-01-19 22:39:12 +00:00
|
|
|
|
private readonly ILogger _logger;
|
2024-01-18 22:13:40 +00:00
|
|
|
|
|
2024-01-19 22:39:12 +00:00
|
|
|
|
public SessionManager(IServiceProvider serviceProvider, ILogger<SessionManager> logger)
|
2024-01-18 22:13:40 +00:00
|
|
|
|
{
|
|
|
|
|
_sessions = [];
|
|
|
|
|
_serviceProvider = serviceProvider;
|
2024-01-19 22:39:12 +00:00
|
|
|
|
_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;
|
2024-01-19 22:39:12 +00:00
|
|
|
|
_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();
|
2024-01-19 22:39:12 +00:00
|
|
|
|
_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
|
|
|
|
}
|
|
|
|
|
}
|