Snowflake/RPG.Services.Core/Session/SessionManager.cs
2024-01-19 17:45:18 +03:00

46 lines
1.2 KiB
C#

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)
{
if (_sessions.TryRemove(session.SessionId, out _))
{
session.Dispose();
}
}
}