2024-01-18 22:13:40 +00:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
|
|
|
|
namespace RPG.Services.Core.Session;
|
|
|
|
|
public class SessionManager
|
|
|
|
|
{
|
|
|
|
|
private readonly ConcurrentDictionary<ulong, RPGSession> _sessions;
|
|
|
|
|
private readonly IServiceProvider _serviceProvider;
|
|
|
|
|
|
|
|
|
|
public SessionManager(IServiceProvider serviceProvider)
|
|
|
|
|
{
|
|
|
|
|
_sessions = [];
|
|
|
|
|
_serviceProvider = serviceProvider;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
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-18 22:13:40 +00:00
|
|
|
|
}
|
|
|
|
|
}
|