Hangfire.Console icon indicating copy to clipboard operation
Hangfire.Console copied to clipboard

Is it possible to inject PerformContext into job constructor?

Open ilya-chumakov opened this issue 6 years ago • 1 comments

To keep job method signatures clean, I tried to inject PerformContext into the job constructor (we use ASP.NET Core built-in DI to resolve jobs). Unfortunately, I got:

System.InvalidOperationException: 'Unable to resolve service for type 'Hangfire.Server.PerformContext' while attempting to activate 'FooJob'.'

Is it possible to use Hangfire.Console this way?

Our packages:

<PackageReference Include="Hangfire.Console" Version="1.4.2" />
<PackageReference Include="HangFire" Version="1.6.19" />
<PackageReference Include="Hangfire.PostgreSql" Version="1.4.8.2" />

ilya-chumakov avatar Jan 28 '19 09:01 ilya-chumakov

Hangfire doesn’t allow constructor injection of PerformContext. Probably because it must be unique for each execution, while a job class itself can be static/singleton. So the answer is "no"… or so it was before 1.7.0.

In dev branch (and 1.7.0 betas), there’s a change in job activation process that passes a full PerformContext now. So in theory, you can create a custom JobActivator that would place PerformContext instance into a newly-created scope, making it available for constructor activation.

pieceofsummer avatar Jan 28 '19 10:01 pieceofsummer