GetScopedService (non wrapped)
964adba3f345a881d7cb3de64c4ed647de96f677
2 files changed
SessionScoped/SessionScoped.csprojSessionScoped/SessionScopedFactory.cs
diff --git a/SessionScoped/SessionScoped.csproj b/SessionScoped/SessionScoped.csproj
index fd02a30..0c406c3 100644
--- a/SessionScoped/SessionScoped.csproj
+++ b/SessionScoped/SessionScoped.csproj
@@ -4,7 +4,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PackageId>Extensions.DependencyInjection.SessionScoped</PackageId>
- <Version>9.0.1</Version>
+ <Version>9.0.2</Version>
<Authors>Alphons van der Heijden</Authors>
<Description>Adds a session-scoped IHostedService service to the services collection</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
diff --git a/SessionScoped/SessionScopedFactory.cs b/SessionScoped/SessionScopedFactory.cs
index 14aa367..8a7f5c3 100644
--- a/SessionScoped/SessionScopedFactory.cs
+++ b/SessionScoped/SessionScopedFactory.cs
@@ -33,13 +33,13 @@ public class SessionScopedFactory<T>(
private readonly ConcurrentDictionary<string, DateTimeOffset> timeout = new();
/// <summary>
- /// Creates a wrapped instance of the scoped service.
+ /// Creates an instance of the scoped service.
/// </summary>
- /// <returns>A wrapped session-scoped service.</returns>
- private SessionScopedWrapper GetScopedServiceWrapped()
+ /// <returns>A session-scoped service.</returns>
+ private T GetScopedService()
{
using var scope = serviceProvider.CreateScope();
- return new(scope.ServiceProvider.GetRequiredService<T>());
+ return scope.ServiceProvider.GetRequiredService<T>();
}
/// <summary>
@@ -57,9 +57,9 @@ public class SessionScopedFactory<T>(
if (!services.TryGetValue(sessionId, out SessionScopedWrapper? wrapper))
{
- wrapper = GetScopedServiceWrapped();
- if (wrapper == null)
+ var service = GetScopedService() ??
throw new InvalidOperationException("Cannot get scoped service.");
+ wrapper = new SessionScopedWrapper(service);
if (services.TryAdd(sessionId, wrapper))
{
wrapper.Start();
@@ -82,7 +82,7 @@ public class SessionScopedFactory<T>(
{
await service.StopAsync();
Logger.LogInformation("Removed stopped service with ID: {sessionId}", sessionId);
- service = null;
+ service = null; // Let the GC collect it
}
// Remove the timeout entry
@@ -116,10 +116,10 @@ public class SessionScopedFactory<T>(
{
try
{
- // Configurable interval duration
+ // Non-Configurable interval duration (good sampling)
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
- // Determine the threshold for expired items
+ // Determine new threshold for expired items
var expirationThreshold = DateTimeOffset.UtcNow.Subtract(sessionTimeout);
var sessionIds = timeout.Where(x => x.Value < expirationThreshold).Select(x => x.Key).ToArray();