Hangfire needs parameterless constructor


I need to start job which will send some notifications.
I have class NotificationsProcessorJob and the method “Do” in it, which will do all the job (you can see code below).
NotificationsProcessorJob class needs some managers for its logic so it have constructor with three parameters.

public class NotificationsProcessorJob
    private readonly IFirstManager firstManager;

    private readonly ISecondManager secondManager;

    private readonly IThirdManager thirdManager;

    public NotificationsProcessorJob(
        IFirstManager firstManager, 
        ISecondManager secondManager, 
        IThirdManager thirdManager)
        this.firstManager = firstManager;
        this.secondManager = secondManager;
        this.thirdManager = thirdManager;

    public void Do()
        //some logic

So, when I start my job like this:

var notificationProcessorJob = new NotificationsProcessorJob(

RecurringJob.AddOrUpdate(() => notificationProcessorJob.Do(), Cron.Minutely);

in the Hangfire Dashboard I can see the next exception:

Failed An exception occurred during job activation.
No parameterless constructor defined for this object.

But when I add default constructor in my class
(just like this:

public NotificationsProcessorJob() { } 


job activation method starts using this default constructor (despite I use the class instance which I create with constructor with parameteres) and my managers in the job class are not initialized.

How can I fix it?

Thanks in advance!

Hangfire doesn’t have access to the object instance that you used when scheduling the job. You need to use dependency injection container to pass in the dependencies in the constructor. See: http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html

Thank you very much! I tried to use JobActivator and it helped me :smile:

I was using JobActivator without luck and then just found the first comment here from, “Sam Shiles” quite helpful

1 Like