Hangfire icon indicating copy to clipboard operation
Hangfire copied to clipboard

Provide some way for cleaning RecurringJob.Instance

Open knopa opened this issue 2 years ago • 2 comments

Issue I have integration tests with separare database instances for write, read in docker so they up one by one Issue is when It switch between database and reset database connection - Recurring Job can't handle connection change because it's has instance which copy old static JobStorage.Current to his variable

knopa avatar Jun 28 '23 22:06 knopa

I think that's is still actual who want to test with testcontainers

But figure out workaround, you can use hangfire in memory for integration tests version and avoid static binding to connection which is changed

knopa avatar Jul 12 '23 07:07 knopa

It's quite late response - but someone might stumble here.

When looking through internals of Hangfire I figured out I am having exactly the same issue - setup testcontainers + Hangfire.

I sadly can't use in memory Hangfire as I have custom tables in Hangfire database - e.g. some JobResultInfo which has foreign key to some Hangfire tables.

I couldn't get resetting through reflection of the static Lazy loaded JobStorage.Current working in the brief amount of time I spent on this issue.

Found some ugly workaround using reflection in which I set the factory field to always retrieve service IBackgroundJobClient from new scope. This is far from ideal but I sadly don't have more time to investigate this issue further.

In ConfigureTestServices I do:

var backgroundJobType = typeof(BackgroundJob);
var clientFactoryField = backgroundJobType.GetField("_clientFactory", BindingFlags.Static | BindingFlags.NonPublic);

if (clientFactoryField != null)
{
	Func<IBackgroundJobClient> newFactory = () =>
	{
		using var scope = services.BuildServiceProvider().CreateScope();
		return scope.ServiceProvider.GetRequiredService<IBackgroundJobClient>();
	};

	clientFactoryField.SetValue(null, newFactory);
}

If anyone finds better way of doing this I would be more than welcome to discuss this.

Now I am off to battle running these tests in GitHub workflows. Support for proper testing is quite bad, wish you all the best.

sebastianstupak avatar Oct 31 '24 12:10 sebastianstupak