Search code examples
c#dependency-injectionhangfire

Recurring Job and injected dependency


Is it possible to dependency inject into a recurring job in Hangfire, and have that injection run for each subsequent run of that job? I've tried this, but I'm guessing once a job is queued its dependencies are serialised its sort of fixed because my dependencies are all null once the job is attempted to be constructed, particularly through the Hangfire UI.


Solution

  • You can inject an instance into your recurring job by using the generic overload:

    RecurringJob.AddOrUpdate<Foo>(“JobId”, x => x.DoSomething(), Cron.Hourly)
    

    This will create an instance of the class using its default constructor, as covered in Passing dependencies in the documentation.

    You can also override this behaviour or use IoC containers such as Ninject. This is covered in Using IoC containers in the documentation.