HangfireIO / HangfireIO/Hangfire
Invalid dependency resolve in BackgroundService
- Dominant language
- C#
- Stars
- 10.1k
- Forks
- 1.8k
- Avg merge
- 1h 19m
- Merged PRs (30d)
- 1
Description
Hi,
We're using Hangfire 1.7.31 on our production system on ASP.NET Core API (.NET6)
Startup.cs (nothing special, almost 1:1 hangfire documentation)
```csharp
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseSerilogLogProvider()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(
_configuration.GetConnectionString("HangfireConnection"),
new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
services.AddHangfireServer(options =>
{
options.Queues = new[] { "default" };
options.ServerName = Environment.MachineName;
options.WorkerCount = 10;
});
```
Our issue it that we wanted to perform some jobs in `BackgroundService` [(DOCS)](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0) but injecting `IBackgroundJobClient` results in `NullRefrenceException` after BackgroundService has started
```csharp
services.AddHostedService(serviceProvider =>
{
var backgroundJobClient = serviceProvider.GetRequiredService();
var logger = serviceProvider.GetRequiredService>();
return new SomeHangfireBackgroundService(backgroundJobClient, logger);
});
```
After the service has started (GetRequiredService does not throw exception), IBackgroundJobClient gets collected by CLR or something and it's null. We're not able to reproduce this error on our development machines, it occurs only on production and it's consistent after many restarts
Is performing tasks in BackgroundService forbidden or we're just doing something wrong?
Contributor guide
Research direction
Start with the Startup.cs registrations and the SomeHangfireBackgroundService constructor shown in the issue, then trace how IBackgroundJobClient is resolved and used after the hosted service starts. Compare the production and development ASP.NET Core API environments and determine why the client is null only in production; done means identifying whether this usage is supported and documenting a reproducible cause or resolution.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100