3

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.Sessionis 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...

  1. ...a Hangfire job, all dependencies Autofac resolves get an user ID based on the job type (e.g. "AcmeJobImporter", "FooJob")
  2. ..the MVC user interface, the id from HttpContextis used

Solution idea:

  1. Replace HttpContextwith a wrapper interface, e.g. ICurrentContext. One implementation returns values from HttpContext, other just uses static ones.

  2. By default, setup Autofac to return the HttpContext-based implementation.

  3. In our Hangfire JobActivator, create a new Autofac (child?) container. Replace the ICurrentContext 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.

Community
  • 1
  • 1
Lauri Harpf
  • 1,448
  • 1
  • 12
  • 30
  • 1
    Seems like ThreadStatic no longer need (https://github.com/HangfireIO/Hangfire/pull/204#issuecomment-125198220). I was able to use fake `HttpContext` with aspnet core DI (https://stackoverflow.com/a/42222736/3009578) – smg Aug 30 '17 at 15:03

0 Answers0