But if I need to use some other .net objects to get my array of queue names (e.g. in my case, connect to a database to look them up) it’s quite hard to do this within ConfigureServices() since no serviceProvider is available and you shouldn’t build one as it’ll create an additional copy of singletons. Does anyone have a good pattern for solving this? The answers here don’t appear straightforward since the AddHangfireServer() method isn’t a trivial AddSingleton() call.
Currently I’m thinking it’ll be easiest to directly instantiate the objects I need within ConfigureServices, before using them to call AddHangfireServer(), but that’s not super simple in my case so I’d love to hear how anyone else has solved this.
Thanks for the reply. My queue names depend on the current system configuration, which can change from time to time, so can’t be constants. Specifically the queues represent which tenants that server is responsible for, and that’s stored in a database. I’ve considered making an IOptions to represent that configuration, and define it’s source from a database. But it feels quite difficult to do all that inside ConfigureServices and ensure it’s available before the call to AddHangfireServer.
private List<string> GetQueuesHangFire(IApplicationBuilder app)
{
using var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope();
using var context = serviceScope.ServiceProvider.GetService<Models.DB.MyCustomContext>();
var res = context.Queues.Select(x => x.Code).ToList();
res.Add("default");
return res;
}
Hi Gon, thanks for that. So you call that from Configure, not ConfigureServices? How are you starting the Hangfire server? The sample for asp.net puts it in ConfigureServices: services.AddHangfireServer() from which the ServiceProvider isn’t available yet.