My ASP.NET MVC 4 application (.NET 4.0) allows users to make orders. The current user's ID in HttpContext
and other information in HttpContext.Session
is used for many purposes, e.g. as the person who placed the order.
We are adding automatic import of orders via Hangfire jobs. Hangfire jobs have no HttpContext
, so a user ID must be provided in another way. We dependency inject with Autofac.
Question: How to inject the current user as a dependency so that when an order is entered via...
- ...a Hangfire job, all dependencies Autofac resolves get an user ID based on the job type (e.g. "AcmeJobImporter", "FooJob")
- ..the MVC user interface, the id from
HttpContext
is used
Solution idea:
Replace
HttpContext
with a wrapper interface, e.g.ICurrentContext
. One implementation returns values fromHttpContext
, other just uses static ones.By default, setup Autofac to return the
HttpContext
-based implementation.- In our Hangfire
JobActivator
, create a new Autofac (child?) container. Replace theICurrentContext
implementation with one that returns the job's name.
This solution worries me, because it seems to require use of ThreadStatic, which might not be OK in ASP.NET MVC context. Is there a better method? I do not want to pass the values as method arguments, since they flow throughout the whole application.