Creating a BatchJob scoped service using Hangfire.Autofac

Hi,

We create Batch jobs with nested Batches and Jobs. The JobActivator uses the Hangfire.Autofac package and UseAutofacActivator when updating IGlobalConfiguration

We would like to have a type registered at the BatchJob level. There is InstancePerBackgroundJob() as shown in the snippet below, is there an equivalent for a BatchJob?

 configuration
       .UseAutofacActivator( builder.Build(), ( builder, context ) =>
       {
           builder.RegisterType<SomeType>().InstancePerBackgroundJob();
       }

How do we register a type (SomeType) to be available for the life time of a BatchJob and all its nested children?

Thanks,
John

Batches consist of regular background jobs, so InstancePerBackgroundJob will also be useful for background jobs that are part of a batch. Have you tried using this?

The way we organise batches means that multiple background jobs are used.
e.g.
An overall batch that consists of three child batches.

  • An Init batch that configures multiple steps consisting of batches and background jobs
  • A Process batch that executes multiple steps consisting of batches and background jobs
  • A Complete batch that finalises multiple steps consisting of batches and background jobs

I would like to resolve the service for the lifetime from Init until Complete

I’m afraid this is not possible, since all the 3 background jobs in a batch don’t share process’ state and can be executed even on different states. So it’s better to store intermediary data in an external storage, by using batch id form example to address it.

Thank you for the update, I’ll have a look at using the batch id