- 首先在Startup.cs文件中注册Hangfire服务:
services.AddHangfire(config => config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
- 然后在Configure方法中启用Hangfire服务和Dashboard:
app.UseHangfireDashboard();
app.UseHangfireServer();
- 在要使用Hangfire的组件中注入相关服务,例如:
public class MyComponent
{
private readonly IBackgroundJobClient _jobClient;
public MyComponent(IBackgroundJobClient jobClient)
{
_jobClient = jobClient;
}
public async Task SomeMethod()
{
await _jobClient.Enqueue(() => DoSomething());
}
public void DoSomething()
{
//Perform some work here
}
}
- 在Blazor Server的组件中使用Inject属性注入Hangfire服务:
@inject IBackgroundJobClient HangfireClient
- 在需要的地方调用Hangfire服务来触发定时作业或后台作业:
HangfireClient.Enqueue(() => DoSomething());