Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if HangFire.JobStorage is instantiated

I have a ASP.NET MVC Application that works as Hangfire client - it enqueues different jobs. I am using SqlServerJobStorage for Hangfire usage.

For now i am working on a scenario when there is no connection to Hangfire Database, and somewhere in the future connection is being instantiated.

The goal is that my ASP.NET MVC Application should keep working before this moment. After connection restores it should start to enqueue jobs.

So application will throw an exception in Global.asax:

Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("EshopServiceHangfire");

Moreover all job enqueues will also throw exceptions:

 BackgroundJob.Enqueue<ISomeClass>(x => x.DoSomethingGreat(JobCancellationToken.Null));

I put the row from Global.asax in a try/catch block, so it will not throw. When somebody enqueue job, i want to check JobStorage.Current and if it is not initialized, i`l try to init it again with the same code:

Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("EshopServiceHangfire");

Does anybody knows a way to do this? Documentation has no information about this.

Something like Hangfire.GlobalConfiguration.JobStorage.IsInitialized ?

Catching exception from Job enqueue also is a way, but i don`t like it, because it throws non specific

InvalidOperationException: JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.

Much appreciated for those who have read up to this place)

like image 900
AlexSolovyov Avatar asked Jun 06 '17 09:06

AlexSolovyov


1 Answers

You could use the Hangfire.JobStorage.Current static property itself to check Hangfire storage configuration:

//InvalidOperationException " JobStorage.Current property value has not been initialized"
var storage = JobStorage.Current;

GlobalConfiguration.Configuration.UsePostgreSqlStorage(vaildConnString);

//no exception
storage = JobStorage.Current;

Moreover, you could query a database to test the connection:

JobStorage.Current.GetConnection().GetRecurringJobs();

Considering exceptions, I think that throwing an InvalidOperationException instead of something like SqlException is correct. Hangfire core isolated from details of a specific database.

like image 118
Ilya Chumakov Avatar answered Oct 21 '22 22:10

Ilya Chumakov