Access to Hangfire's distributed lock logic

distributed-locks
Tags: #<Tag:0x00007f49a0048f80>

#1

Hi, I remember a few years back stumbling into some Hangfire class that allowed to use the internal distributed lock logic.
I don’t remember exactly what the line of code was but it allowed to do something like this:

class.AquireLock(“ResourceName”);

This was available on an old Hangfire version.
Is it still possible to access this?
I searched the documentation and tried to find it in the code but I couldn’t find it yet.
I need to use a distributed lock in my application and instead of implementing the logic from scratch I could simply use Hangfire’s logic, since the application already depends on it.


#4

So, this is what you have to do if you want to use Hangfire’s distributed lock logic.
The first thing is to add the following line on your ConfigureServices method:

services.AddScoped(e => new SqlServerStorage("YourConnectionString));

And then you have to inject that dependency in the constructor of your service (or class where you want to use the distributed lock).
An updated version of the original example is shown bellow.

using Hangfire.SqlServer;

namespace MyNamespace
{
    public class MyService
    {
        private static readonly TimeSpan distributedLockTimeSpan;
        private readonly SqlServerStorage hangfireSqlServerStorage;
        
        static MyService()
        {
            distributedLockTimeSpan = new TimeSpan(0, 0, Configuration.GetParameter<int>("ApplicationSettings:DistributedLockTimeoutInSeconds"));
        }

        public MyService(ISqlServerStorage hangfireSqlServerStorage)
        {
            this.hangfireSqlServerStorage = hangfireSqlServerStorage;
        }

        public void MyMethod(long id)
        {
            using (this.hangfireSqlServerStorage.GetConnection().AcquireDistributedLock($"MyResource_{id}", distributedLockTimeSpan))
            {
		//My custom code
            }
        }
    }
}