using Microsoft.Extensions.DependencyInjection; namespace Connected.ServiceModel { internal sealed class Context : IContext, IDisposable { private CancellationTokenSource _cancellationTokenSource; public Context() { _cancellationTokenSource = new(); } public CancellationToken CancellationToken => _cancellationTokenSource.Token; internal IServiceScope? Scope { get; set; } private bool IsDisposed { get; set; } public T? GetService() { if (Scope is null) return default; try { return Scope.ServiceProvider.GetService(); } catch (ObjectDisposedException) { return default; } } public object? GetService(Type serviceType) { if (Scope is null) return default; return Scope.ServiceProvider.GetService(serviceType); } private void Dispose(bool disposing) { if (IsDisposed) return; if (disposing) { if (!_cancellationTokenSource.IsCancellationRequested) _cancellationTokenSource.Cancel(false); Scope?.Dispose(); _cancellationTokenSource.Dispose(); } IsDisposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }