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?
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
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.
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.CreateInstancemethod 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.