0

So I have setup hangfire with autofac to manage class instantiation with a constructor that uses a paramater. We have a multiple db setup so each time a class is instantiated it takes a dbConnectionString and creates all relevant repos. Now this is how I have managed to register these components.

var builder = new ContainerBuilder();
      Hangfire.GlobalConfiguration.Configuration
             .UsePostgreSqlStorage(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);

      builder.Register(c => new SomeRepoClass("someConnectionString"));

      Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(builder.Build());

      app.UseHangfireDashboard();
      app.UseHangfireServer();

This works just fine but my challenge now is. How do I tell hangfire autofac upon queing a job which connection string to use when it instantiates the class under the hood?

This is how I currently queue a job.

 BackgroundJob.Enqueue(() => _someInstantiatedRepo.SomeMethod(aParam));

I have read the docs and saw something like this.

var reader = Scope.Resolve<IConfigReader>(new NamedParameter("configSectionName", "sectionName"));

This code snippet is from the autofac docs. But I am not too sure how I would go about telling hangfire to use the correct connectionstring when queuing jobs.

In my mind this is how I imagine it working.

//somehow tell hangfire to use this constructor param
//Scope.Resolve<SomeRepoClass>(new NamedParameter("connString", "db-001"));
 BackgroundJob.Enqueue(() => _someInstantiatedRepo.SomeMethod(aParam));

I hope this is enough information.

BinaryMan
  • 1
  • 2
  • Resolving the repository before enqueuing the job won't work. You need to pass the current the tenant (the discriminator value which allows you to select the correct connection string) to hangfire so that your repository is instantiated on the job processing side in the correct context. This may help a little https://stackoverflow.com/a/57396553/1236044 Somewhere in your code there must be a ConnectionString provider, a service class which returns the correct connection string depending on the context. You should start from there in the dependency chain allowing to instantiate a repository – jbl Sep 14 '21 at 09:29

0 Answers0