Does hangfire instantiate the static objects in a class everytime a job is created?


#1

I have a class as shown below with a static object used for caching some values to avoid going to the DB all the time for it.
When the DoWork method is enqueued and the job is executed by hangfire, is the object loaded once or multiple times?

public class SomeClass
{
    private static SomeData myCache = LoadValuesFromDb();

    private static SomeData LoadValuesFromDb()
    {
	//Reads some values from DB
    }

    public void DoWork(int id)
    {
	//Uses myCache to do some work.
    }
}

for(int i = 0; i < 10; i++)
{
    BackgroundJob.Enqueue<SomeClass>(x => x.DoWork(i));
}

#2

It is not actually Hangfire, it’s just static fields are initialized when the type is referenced for the first time.

You may want to make myCache lazy (so it would be loaded only when it is actually accessed, instead of when the type is loaded):

private static readonly Lazy<SomeData> myCache = new Lazy<SomeData>(LoadValuesFromDb);

Type initializers are executed once per AppDomain, so if your Hangfire server runs in the same AppDomain as client, the cache will be loaded just once.