Search code examples
c#.nethangfire

AddHangfireServer with additional processes


I am getting started with Hangfire and building it to run the background jobs in a console app instead of aspnet. I see that the sqlstorage has background processes and want to add an additional one. There is an argument on AddHangfireServer to include additional processes, however, it requires the JobStorage. While ConfiguringServices JobStorage.Current throws an exception Current JobStorage instance has not been initialized yet. I did find that I can create a descendant of the SqlStorage and add an item to GetComponents but it is marked Obsolete. How can I set this using the non-obsolete method?

private static void Main(string[] args) {
            var host = Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((ctx, cb) => ConfigBuilder(cb, args))
                .ConfigureServices((ctx, svcColl) => ConfigureServices(svcColl, ctx.Configuration))
                .ConfigureLogging(Configurelogging)
                .Build()
                .Run();
}

private static void ConfigureServices(IServiceCollection services, IConfiguration cfg) {
    var dbcs = cfg.GetValue<string>("ConnectionStrings:DB");
    _ = services.AddHangfire(gc => {
        _ = gc
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseSqlServerStorage(dbcs);
    });

    _ = services.AddHangfireServer(JobStorage.Current, new[] { new MyProcess { } });
}

Solution

  • Current JobStorage instance has not been initialized yet

    As answered here jobstorage not initialized

    You should call JobStorage.Current = new SqlServerStorage("ConnectionStringName", options) before initializing your BackgroundJobServer.

    Now regarding this

    I see that the sqlstorage has background processes and want to add an additional one

    Option 1

     JobStorage.Current = new SqlServerStorage("connectionString");
     _ = services.AddHangfireServer(storage: JobStorage.Current , additionalProcesses: new[] { new MyProcess()} );
    

    Option 2

    Any class registered in the DI as IBackgroundProcess is automatically added as an additional service

    IBackgroundProcess. From the source code, You simply have your class implement this interface and register it in the DI Container, it will interrogate your DI container via services.GetServices to get any registrations you've made.

      services.AddTransient<IBackgroundProcess, BackgroundWorker>();
    

    and then in here there will be no need to add it under additional processes

    JobStorage.Current = new SqlServerStorage("connectionString");
    
    _ = builder.Services.AddHangfireServer(storage: JobStorage.Current);