How to use hangfire in .net core with mongodb?

Viewed 5358

I want to use Hangfire for background jobs in registration form process,But I am unable to find Startup.cs file code for Hangfire.mongo.

3 Answers

Just an update to this thread,

As of v0.7.11, MongoMigrationOptions have been updated and no longer contains Strategy. As per the release notes, you now have to use MigrationStrategy instead of Strategy. Also, the values you use for these are different as well. See example below.

var migrationOptions = new MongoMigrationOptions
{
    MigrationStrategy = new MigrateMongoMigrationStrategy(),
    BackupStrategy = new CollectionMongoBackupStrategy()
};

In Startup class In ConfigureServices method Add

//you will use some way to get your connection string
var mongoConnection = Configuration.GetConnectionString("MongoDBAtlasJaken");
var migrationOptions = new MongoMigrationOptions
{
    Strategy = MongoMigrationStrategy.Drop,
    BackupStrategy = MongoBackupStrategy.Collections
};

services.AddHangfire(config =>
{
    config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
    config.UseSimpleAssemblyNameTypeSerializer();
    config.UseRecommendedSerializerSettings();
    config.UseMongoStorage(mongoConnection, "Hangfire",new MongoStorageOptions {   MigrationOptions = migrationOptions });

});
services.AddHangfireServer();

In Configure method you can add if you want

app.UseHangfireDashboard();

@Graeme's anwser works on the older version of Hangfire. For the new version,

  1. The Migration and Backup strategy are changed to class from enum.

     var migrationOptions = new MongoMigrationOptions
     {
         MigrationStrategy = new DropMongoMigrationStrategy(),
         BackupStrategy = new CollectionMongoBackupStrategy()
     };
    
  2. The UseMongoStorage method does not accept the collection name anymore.

     services.AddHangfire(config =>
     {
         config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
         config.UseSimpleAssemblyNameTypeSerializer();
         config.UseRecommendedSerializerSettings();
         config.UseMongoStorage(mongoConnection, new MongoStorageOptions { MigrationOptions = migrationOptions, CheckConnection = false });
     });
    

    services.AddHangfireServer();

Related