Skip to content

Commit

Permalink
Add scoped service resolution for PingHelper in Hangfire job
Browse files Browse the repository at this point in the history
  • Loading branch information
nenad0707 committed Jun 6, 2024
1 parent 1e71bca commit 304feb7
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions TodoApi/StartupConfig/HangfireMiddlewareExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Hangfire;
using Microsoft.Extensions.DependencyInjection;
using TodoApi.Helpers;

namespace TodoApi.StartupConfig;
Expand All @@ -14,18 +15,23 @@ public static class HangfireMiddlewareExtensions
/// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
public static IApplicationBuilder UseHangfireJobs(this IApplicationBuilder app)
{
var serviceProvider = app.ApplicationServices;
var pingHelper = serviceProvider.GetRequiredService<PingHelper>();
var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();

RecurringJob.AddOrUpdate(
"PingApi",
() => pingHelper.PingApiWithRetry(),
"*/15 * * * *"); // Adjust to "*/5 * * * *" if needed
using (var scope = serviceScopeFactory.CreateScope())
{
var pingHelper = scope.ServiceProvider.GetRequiredService<PingHelper>();

RecurringJob.AddOrUpdate(
"PingApi",
() => pingHelper.PingApiWithRetry(),
"*/15 * * * *"); // Adjust to "*/5 * * * *" if needed

RecurringJob.AddOrUpdate(
"PingDatabase",
() => pingHelper.PingDatabaseWithRetry(),
"*/15 * * * *"); // Adjust to "*/5 * * * *" if needed
}

RecurringJob.AddOrUpdate(
"PingDatabase",
() => pingHelper.PingDatabaseWithRetry(),
"*/15 * * * *"); // Adjust to "*/5 * * * *" if needed
return app;
}
}

0 comments on commit 304feb7

Please sign in to comment.