How to seed Hangfire database in asp.net core 2.0

685 views Asked by At

I'm trying to integrate "Hangfire" to my existing ASP.NET Core application. Looking into the documentaion, looks like the Hangfire db needs to be created if we want to use SQL Server storage option. But it would be really annoying to create a db every time we spin up a new server.

Is there a way I could seed DB with the SQL Storage option enabled rather than from startup class like this?

 services.AddHangfire(options =>
            options.UseSqlServerStorage(Configuration["HangfireConnection"]));
1

There are 1 answers

1
Denny Puig On

A good solution could be to isolate this concern to some TSQL scripts and run those scripts when the app startup or before running your tests (based on your scenario), but a quick solution that I have used before is something like this (based on this post).

public class HangfireContext : DbContext
{
    public HangfireContext(DbContextOptions options)
        : base(options)
    {
        Database.EnsureCreated();
    }
}


public class Startup
{

   public void ConfigureServices(IServiceCollection services)
   {
      var connectionString = Configuration.GetConnectionString("HangfireConnectionString");
      var optionsBuilder = new DbContextOptionsBuilder<HangfireContext>();
      optionsBuilder.UseSqlServer(connectionString);
      var hangfireDbContext = new HangfireContext(optionsBuilder.Options);

      services.AddHangfire(config =>
                config.UseSqlServerStorage(connectionString));
   }
}