Skip to content

Commit

Permalink
Clear HttpContext in background, also allows bg job from bg task. (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
jtkech authored Aug 15, 2023
1 parent 9b44b9e commit 25b098b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public static Task ExecuteAfterEndOfRequestAsync(string jobName, Func<ShellScope
return Task.CompletedTask;
}

// Can't be executed outside the context of a real http request scope.
// Can't be executed outside of an http context.
var httpContextAccessor = scope.ServiceProvider.GetRequiredService<IHttpContextAccessor>();
if (httpContextAccessor.HttpContext == null || httpContextAccessor.HttpContext.Items.TryGetValue("IsBackground", out _))
if (httpContextAccessor.HttpContext == null)
{
return Task.CompletedTask;
}
Expand Down Expand Up @@ -57,7 +57,7 @@ public static Task ExecuteAfterEndOfRequestAsync(string jobName, Func<ShellScope
return;
}
// Initialize a new 'HttpContext' to be used in the background.
// Create a new 'HttpContext' to be used in the background.
httpContextAccessor.HttpContext = shellContext.CreateHttpContext();
// Here the 'IActionContextAccessor.ActionContext' need to be cleared, this 'AsyncLocal'
Expand Down Expand Up @@ -87,6 +87,9 @@ await ShellScope.UsingChildScopeAsync(async scope =>
scope.ShellContext.Settings.Name);
}
});
// Clear the 'HttpContext' for this async flow.
httpContextAccessor.HttpContext = null;
});

return Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ await GetShellsToRun(runningShells).ForEachAsync(async shell =>
{
var tenant = shell.Settings.Name;
// Create a new 'HttpContext' to be used in the background.
_httpContextAccessor.HttpContext = shell.CreateHttpContext();
var schedulers = GetSchedulersToRun(tenant);
Expand Down Expand Up @@ -182,6 +183,9 @@ await shellScope.UsingAsync(async scope =>
await handlers.InvokeAsync((handler, context, token) => handler.ExecutedAsync(context, token), context, stoppingToken, _logger);
});
}
// Clear the 'HttpContext' for this async flow.
_httpContextAccessor.HttpContext = null;
});
}

Expand All @@ -198,6 +202,7 @@ await GetShellsToUpdate(previousShells, runningShells).ForEachAsync(async shell
return;
}
// Create a new 'HttpContext' to be used in the background.
_httpContextAccessor.HttpContext = shell.CreateHttpContext();
var shellScope = await _shellHost.GetScopeAsync(shell.Settings);
Expand Down Expand Up @@ -273,6 +278,9 @@ await shellScope.UsingAsync(async scope =>
scheduler.Updated = true;
}
});
// Clear the 'HttpContext' for this async flow.
_httpContextAccessor.HttpContext = null;
});
}

Expand Down

0 comments on commit 25b098b

Please sign in to comment.