Search code examples
c#asp.net-web-apihangfireasp.net-core-6.0

ASP.NET Core Web API - How to resolve The name 'AddCronJobConfigurations' does not exist in the current context


In ASP.NET Core-5 Web API, I have this:

Startup.cs:

public void Configure(IApplicationBuilder app,
    IWebHostEnvironment env,
    IRecurringJobManager recurringJobManager,
    IServiceProvider serviceProvider)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseHangfireDashboard();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });

    var branchService = serviceProvider.GetService<IAdminBranchService>();

    recurringJobManager.AddOrUpdate("Post_All_Branches", () => branchService.CreateBranchAsync(), Cron.Minutely);
}

But now I am using ASP.NET Core-6 Web API. So for the HangFire CronJob I created a class as shown here:

public static class CronJobExtension
{
    public static void AddCronJobConfigurations(IRecurringJobManager recurringJobManager, IServiceProvider serviceProvider)
    {
        var branchService = serviceProvider.GetService<IAdminBranchService>();

        recurringJobManager.AddOrUpdate("Post_All_Branches", () => branchService.CreateBranchAsync(), Cron.Minutely);
    }
}

So in I only have Program.cs. Then I referenced AddCronJobConfigurations in Program.cs.

Program.cs:

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseHangfireDashboard();

AddCronJobConfigurations();

But I got this error:

Error CS0103 The name 'AddCronJobConfigurations' does not exist in the current context

How do I get this resolved?

Thanks


Solution

  • You can do this:

    CronJobExtension.AddCronJobConfigurations(recurringJobManager ,serviceProvider);
    

    Or use this keyword to create an extension method:

    public static class CronJobExtension
    {
        public static void AddCronJobConfigurations(this IServiceProvider serviceProvider, IRecurringJobManager recurringJobManager)
        {
            var branchService = serviceProvider.GetService<IAdminBranchService>();
    
            recurringJobManager.AddOrUpdate("Post_All_Branches", () => branchService.CreateBranchAsync(), Cron.Minutely);
        }
    }
    

    and use it the same way, with slightly different syntax:

    serviceProvider.AddCronJobConfigurations(recurringJobManager);