Joe*_*lty 7 c# hangfire .net-core asp.net-core
我正在使用 HangFire 在后台定期向用户发送电子邮件。
我正在从数据库中获取电子邮件地址,但我不确定是否将数据库上下文“注入”到负责正确发送电子邮件的服务中
这工作正常,有没有更好的方法来做到这一点?
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Context context)
{
(...)
app.UseHangfireDashboard();
app.UseHangfireServer(new BackgroundJobServerOptions
{
HeartbeatInterval = new System.TimeSpan(0, 0, 5),
ServerCheckInterval = new System.TimeSpan(0, 0, 5),
SchedulePollingInterval = new System.TimeSpan(0, 0, 5)
});
RecurringJob.AddOrUpdate(() => new MessageService(context).Send(), Cron.Daily);
(...)
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
public class MessageService
{
private Context ctx;
public MessageService(Context c)
{
ctx = c;
}
public void Send()
{
var emails = ctx.Users.Select(x => x.Email).ToList();
foreach (var email in emails)
{
sendEmail(email, "sample body");
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 13
我只是看了类似的问题,并没有在一个地方找到信息,所以在这里发布我的解决方案。
假设您已Context配置为服务,即
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
....
services.AddDbContext<Context>(options => { ... });
....
}
Run Code Online (Sandbox Code Playgroud)
这使得IServiceProvider能够解决Context依赖关系。
接下来,我们需要更新MessageService类,以便不Context永久保存,而是仅实例化它以执行任务。
public class MessageService
{
IServiceProvider _serviceProvider;
public MessageService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Send()
{
using (IServiceScope scope = _serviceProvider.CreateScope())
using (Context ctx = scope.ServiceProvider.GetRequiredService<Context>())
{
var emails = ctx.Users.Select(x => x.Email).ToList();
foreach (var email in emails)
{
sendEmail(email, "sample body");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后我们要求HangfireMessageService为我们实例化,它也会IServiceProvider为我们解决依赖:
RecurringJob.AddOrUpdate<MessageService>(x => x.Send(), Cron.Daily);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4489 次 |
| 最近记录: |