Hangfire dependency injection with .net core

后端 未结 8 1866
孤城傲影
孤城傲影 2020-12-08 02:02

How can I use .net core\'s default dependency injection in Hangfire ?

I am new to Hangfire and searching for an example which works with asp.net core.

相关标签:
8条回答
  • 2020-12-08 02:32

    If you are trying to quickly set up Hangfire with ASP.NET Core (tested in ASP.NET Core 2.2) you can also use Hangfire.MemoryStorage. All the configuration can be performed in Startup.cs:

    using Hangfire;
    using Hangfire.MemoryStorage;
    
    public void ConfigureServices(IServiceCollection services) 
    {
        services.AddHangfire(opt => opt.UseMemoryStorage());
        JobStorage.Current = new MemoryStorage();
    }
    
    protected void StartHangFireJobs(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.UseHangfireServer();
        app.UseHangfireDashboard();
    
        //TODO: move cron expressions to appsettings.json
        RecurringJob.AddOrUpdate<SomeJobService>(
            x => x.DoWork(),
            "* * * * *");
    
        RecurringJob.AddOrUpdate<OtherJobService>(
            x => x.DoWork(),
            "0 */2 * * *");
    }
    
    public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        StartHangFireJobs(app, serviceProvider)
    }
    

    Of course, everything is store in memory and it is lost once the application pool is recycled, but it is a quick way to see that everything works as expected with minimal configuration.

    To switch to SQL Server database persistence, you should install Hangfire.SqlServer package and simply configure it instead of the memory storage:

    services.AddHangfire(opt => opt.UseSqlServerStorage(Configuration.GetConnectionString("Default")));
    
    0 讨论(0)
  • 2020-12-08 02:34

    Currently, Hangfire is deeply integrated with Asp.Net Core. Install Hangfire.AspNetCore to set up the dashboard and DI integration automatically. Then, you just need to define your dependencies using ASP.NET core as always.

    0 讨论(0)
提交回复
热议问题