1

I've got an asp.net 5 web app using standard .net Dependency Injection. As I understand it, out of the box Hangfire will use the same dependencies for instantiating jobs as MVC will for controllers etc. I'd like to inject a different dependency when instantiating jobs. How can I do this?

e.g. some classes have dependencies on IHttpContextAccessor so I want to provide an alternative for use within hangfire jobs that will get its state from serialized job parameters instead.

I see some discussion here of complex things that sounds like what I need ... but I'd love a simple example :-)

zhulien
  • 4,274
  • 3
  • 15
  • 31
Rory
  • 38,561
  • 50
  • 162
  • 246
  • You want to use a provider or factory pattern. Take a look at this answer. https://stackoverflow.com/a/44177920/860539 – PeteGO Mar 13 '21 at 21:29
  • I would say that you should avoid using the web-context-oriented IHttpContextAccessor out of the direct request processing (out of the controllers). Your controller should build a Poco to pass to the business handling class, which would be the same parameter passed when called through hangfire. Anyway, if changing the business code is not a viable option, I would try decorating the IHttpContextAccessor, providing my own implementation when the decorated accessor has no httpcontext to provide. https://andrewlock.net/adding-decorated-classes-to-the-asp.net-core-di-container-using-scrutor/ – jbl Mar 15 '21 at 16:47
  • Depending on what you want to pass as context information from IHttpContextAccessor you may also use filters https://stackoverflow.com/a/57396553/1236044 – jbl Mar 15 '21 at 16:52

1 Answers1

0

I ended up not using dependency injection to achieve this different behaviour. Instead I changed the classes that use IHttpContentAccessor to alternatively derive the 'tenant' from state set within my Hangfire job methods.

  • In my job methods I first set the tenant in a 'Scoped' object, based on a parameter to the job method
  • In the class that uses IHttpContentAccessor to get info from the current request I first look if there is a current request to get tenant info, and if not I check for that scoped object that's only set during hangfire jobs.
  • In my job methods I don't use constructor dependency injection. Instead I use the service locator (anti)-pattern within the job method. This means I can set the tenant state first before asking for objects that are depended upon it.
Rory
  • 38,561
  • 50
  • 162
  • 246