如何将从 HttpContext 检索到的值传递给 BackgroundJob.Enqueue

How to pass a value retrieved from HttpContext to BackgroundJob.Enqueue

我的控制器中有这段代码:

var user = HttpContext == null ? null 
                               : HttpContext.Items["ApplicationUser"] as ApplicationUser;
int organisationid = user == null ? 0
                                  : user.OrganisationID;
BackgroundJob.Enqueue(() => Merge(organisationid));

所以后台作业在我的控制器中调用 Merge 方法:

public void Merge(int organisationid)
{
    _Uow.MergeSHQSCostsTable(organisationid);
}

但我希望合并方法中的调用使用从请求中检索到的 organisationid,并且在调用 Enqueue 时可用。我怎么做?目前我的代码总是传递零值,因为当后台作业为 运行.

HttpContext 为空

诀窍是将对 BackgroundJob.Enqueue 的调用封装在一个单独的方法中,以便 Hangfire 可以序列化参数:

public SHQSController(IUnitOfWork uow) : base(uow)
{
   //CurrentOrganisationID is retrieved from HttpContext
   EnqueueMerge(CurrentOrganisationID);
}

private void EnqueueMerge(int organisationid)
{
    BackgroundJob.Enqueue(() => Merge(organisationid));
}