如何使用hangfire作业和entityframework添加sqlserver的数据库

问题描述 投票:0回答:1

嗨,我已经在startup.cs中挂起并运行了,并且仪表板正在运行,但是我想每分钟添加一次作业以向sqlserver数据库添加字段。您能帮我吗?

.net entity-framework hangfire
1个回答
0
投票

我已经实现了将数据存储到db的服务类。将用于重复性工作

public interface ITestService{
    Task SaveData();
}
public class TestService : ITestService{

private readonly ApplicationDbContext _dbContext;

   public TestService(ApplicationDbContext dbContext)
   {
       _dbContext = dbContext;
   }

   public async Task SaveData()
   {
       _dbContext.Users.Add(new User
       {
           UserName = "testUser",
           Email = "[email protected]"
       });

    await _dbContext.SaveChangesAsync();
    }
}

在startup.cs中的ConfigureServices()内部,我已经用dbcontext和serviceClass注册了hangfire,它将把数据保存到数据库中

services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
services.AddHangfireServer();

services.AddTransient<ApplicationDbContext>(); //Your DbContext
services.AddTransient<ITestService, TestService>(); //Your Service to store data

在同一文件中,将configure方法更改为,

 Configure(IApplicationBuilder app, IHostingEnvironment env, IRecurringJobManager recurringJobManager, ITestService testService)

在上述方法内部添加调用以下方法

app.UseHangfireDashboard();

recurringJobManager.AddOrUpdate("First recurring job", () => testService.SaveData(), Cron.MinuteInterval(1)); //Instead of the Cron.MinuteInterval() you can use cron expressions
© www.soinside.com 2019 - 2024. All rights reserved.