Search code examples
c#dependency-injectionexpressionhangfire

DI service state when executed inside hangFire job


Help! When we put an expression in a hangFire job, and for example, in this expression we use some services (DI services that work with database)

When doing a hangFire job, are these services snapshots of the state at the time the job was created?

or will these services reflect the real state in which the application is at the time the HF Job is executed?


Solution

  • Hangfire just serializes the MethodInfo (including class/interface type) and the arguments of the method.

    When the job should be processed it requests an instance from DI for the defined class or interface.

    If DI doesn't provide an instance and the type is a class it tries to create an instance of that class. If the class has constructor arguments it tries to receive instances of these arguments also through DI (recursive) or calls the default constructor if available.

    So, mainly it is up to DI if fresh instances are used or not and all jobs are run in their own scope, which means only Singletons are shared.

    Clearly if process A creates a job and process B processes it, nothing will be shared through DI and must be shared through a database, distributed cache, blob storage or similar.