【发布时间】:2018-07-01 17:30:19
【问题描述】:
编辑摘要
我有一个后台服务,它需要一个 DBContext,我的 DbContext 依赖于 HttPContext,因为它使用 UserClaims 来过滤上下文。从 BackgroundService 请求 DbContext 时为 null 的 HttpContext(这是设计使然,因为没有与 BackgroundService 关联的 WebRequest)。
如何捕获和 moq HTTPContext,以便我的用户声明将转移到后台服务?
我正在编写一个托管服务,以便在 Signalr 中对来自我的集线器的推送消息进行排队。我的背景。
public interface IBackgroundTaskQueue
{
void QueueBackgroundWorkItem(Func<IServiceProvider, CancellationToken, Task> workItem);
Task<Func<IServiceProvider, CancellationToken, Task>> DequeueAsync(CancellationToken cancellationToken);
}
public class BackgroundTaskQueue : IBackgroundTaskQueue
{
private ConcurrentQueue<Func<IServiceProvider, CancellationToken, Task>> _workItems = new ConcurrentQueue<Func<IServiceProvider, CancellationToken, Task>>();
private SemaphoreSlim _signal = new SemaphoreSlim(0);
public void QueueBackgroundWorkItem(Func<IServiceProvider, CancellationToken, Task> workItem)
{
if (workItem == null)
{
throw new ArgumentNullException(nameof(workItem));
}
this._workItems.Enqueue(workItem);
this._signal.Release();
}
public async Task<Func<IServiceProvider, CancellationToken, Task>> DequeueAsync(
CancellationToken cancellationToken)
{
await this._signal.WaitAsync(cancellationToken);
this._workItems.TryDequeue(out var workItem);
return workItem;
}
}
我正在排队需要我的 DbContext 的工作项,我的 Db 上下文会根据登录用户自动过滤数据,因此它需要访问 HTTPContextAccessor。
当我排队需要我的 DbContext 的项目时,我收到 HTTPContext 为空的错误,这是有道理的,因为我正在后台进程中运行。
var backgroundTask = sp.GetRequiredService<IBackgroundTaskQueue>();
backgroundTask.QueueBackgroundWorkItem((isp, ct) => {
//When this line is executed on the background task it throws
var context = sp.GetService<CustomDbContext>();
//... Do work with context
});
我的 DBContext 使用 HTTPContextAccessor 过滤数据:
public CustomDbContext(DbContextOptions options, IHttpContextAccessor httpContextAccessor)
{
}
有没有一种方法可以捕获每个任务的 HTTPContext,或者可能是 Moq 一个并捕获 UserClaims,并在 BackgroundService 的范围内替换它们?
如何从我的后台服务中使用依赖于 HTTPContext 的服务。
【问题讨论】:
-
创建任务时为什么不坚持用户原则?
-
@Nkosi 我的 dbContext 接受了 httpcontextaccessor,如何替换该范围内的 httpcontextaccessor?
-
啊。我不知道那件事。 (假设用于审计或其他什么?)你能包括那个小金块吗?应该可以帮助我看到更大的图景。
-
我现在就编辑一下
-
您已经用
asp.net-core标记了这个问题,但我不清楚与您的代码相关的请求是在哪里处理的。你能帮忙解释一下这部分吗?
标签: c# asp.net-core dependency-injection signalr background-process