How to keep job state between runs?

recurring
Tags: #<Tag:0x00007f49a4121548>

#1

I have an instance of a class with a heavy constructor where all initialization happens. Then recurring job calls Execute method to make work done using instantiated stuff. Is there a way to keep this class instance between executions and not initialize from scratch?


#2

Built in to Hangire? No.

Are you using Dependency Injection container (Unity / AutoFac / StructureMap)?
If so, you could do some trickery with the container and the JobActivationContext to get them to cache those objects.

Or just go the cheap and effective way. Don’t put them in the contructor, create those things statically (before you even start up the hangfire backgroundjobserver) and just use the static instance from inside your job method


#3

using Ninject.

interesting, even if I do something like

            var d = new DistributionJob();
            RecurringJob.AddOrUpdate(() => d.Execute(), Cron.Minutely);

in Startup.Configuration (hangfire hosted in MVC project). Each minute constructor got executed. Very weird.


#4

Found answer in docs:

When a worker sees that the given method is an instance-method, it will activate its class first. By default, the Activator.CreateInstance method is used, so only classes with default constructors are supported by default. But you can plug in your IoC container and pass the dependencies through the constructor.