A Step-by-Step Guide to Implementing Hangfire in an MVC Project using C#

Hangfire is an open-source library that allows you to perform background processing tasks in .NET applications. With Hangfire, you can easily run tasks in the background, on a schedule, or in response to certain events. It is a simple yet powerful way to add background processing capabilities to your applications. In this guide, we will walk you through the process of implementing Hangfire in an MVC project using C#. You will learn how to configure Hangfire, create background jobs, and monitor their progress using the Hangfire dashboard.

Sure, here’s a step-by-step guide to implementing Hangfire in an MVC project using C#:

Step 1: Install Hangfire packages

  • Open the Package Manager Console (PMC) in Visual Studio.
  • Type the following command in the PMC: Install-Package Hangfire and press Enter. This will install the Hangfire packages in your project.

Step 2: Configure Hangfire in your project

  • Open the Startup.cs file in your project and add the following code in the ConfigureServices() method:
public void ConfigureServices(IServiceCollection services)
{
    // Add Hangfire services
    services.AddHangfire(configuration => configuration.UseSqlServerStorage("<connection-string>"));
 
    // Add MVC services
    services.AddControllersWithViews();
}
  • Replace <connection-string> with the connection string to your SQL Server database.

Step 3: Configure Hangfire dashboard in your project

  • Add the following code to the Configure() method in the Startup.cs file:
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Add Hangfire dashboard
        app.UseHangfireDashboard();
     
        // Add Hangfire server
        app.UseHangfireServer();
     
        // Add MVC
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    
    • This will add the Hangfire dashboard to your project and configure it to use SQL Server storage.

    Step 4: Create a Hangfire job

    • In the HomeController.cs file, add the following code:
      public class HomeController : Controller
      {
          public IActionResult Index()
          {
              BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
       
              return View();
          }
      }
      
      • This will create a Hangfire job that writes “Hello, world!” to the console.

      Step 5: Run the project and check the Hangfire dashboard

      • Run the project and go to the Hangfire dashboard by adding “/hangfire” to the URL.
      • You should see the job you created in Step 4 under the “Jobs” tab.
      • You can click on the job to see its details and status.

      That’s it! You have successfully implemented Hangfire in your MVC project. You can now create and manage background jobs using Hangfire.

 

Background Methods

BackgroundJob.Enqueue<IEmailSender>(x => x.Send("hangfire@example.com"));
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));

 

Sample Startup Configuration

using Hangfire;
using Notifications.App_Start;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Notifications.Startup))]

namespace Notifications
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            //ConfigureAuth(app);

            GlobalConfiguration.Configuration
                .UseSqlServerStorage("DefaultConnection");
            app.UseHangfireDashboard("/Dashboard", new DashboardOptions
            {
                Authorization = new[] { new MyAuthorizationFilter() }
            });
            app.UseHangfireDashboard();
            app.UseHangfireServer();
        }
    }
}

 

Spread the love

Similar Posts