using Microsoft.Extensions.Hosting; namespace Microsoft.Extensions.DependencyInjection; /// /// Wrapper for an IHostedService, designed for session-based execution. /// This wrapper ensures that a hosted service can be started and stopped /// based on the lifecycle of a session, providing greater control over /// session-specific tasks. It integrates seamlessly with session management /// by allowing services to be dynamically tied to a session's lifetime. /// public class SessionScopedWrapper(IHostedService hostedService) { /// /// The hosted service that is being wrapped. /// public readonly IHostedService hostedService = hostedService; /// /// A CancellationTokenSource used to cancel the task. /// private CancellationTokenSource? cts; /// /// The task that is running for the hosted service. /// private Task? runningTask; /// /// Starts the hosted service. /// public void Start() { cts = new CancellationTokenSource(); runningTask = hostedService.StartAsync(cts.Token); } /// /// Stops the hosted service and cancels the task. /// /// A task representing the asynchronous operation. public async Task StopAsync() { if (cts != null) { cts.Cancel(); try { await hostedService.StopAsync(cts.Token); if (runningTask != null) await runningTask; } catch (AggregateException) { // Suppress exceptions caused by task cancellation } cts.Dispose(); } } }