在.NET Core 2.1中配置Hangfire
我需要根据用户选择的数据库连接字符串在.NET Core 2.1项目中配置hangfire.
I need to configure the hangfire inside .NET Core 2.1 project based on database connectionstring selected by user.
我尝试过的方法:-
我添加了必需的NuGet软件包(Owin和Hangfire),并在 Startup (Startup.cs)类的 Configure 方法中配置了hangfire,如下所示
I have added required NuGet packages(Owin and Hangfire) and configure the hangfire inside Configure method of Startup(Startup.cs) class as follows
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor httpContextAccessor)
{
//Other required code goes here
var storage1 = new Hangfire.SqlServer.SqlServerStorage(ConfigurationManager.AppSettings["DatabaseConnectionString"]);
app.UseHangfireDashboard("/Dashboard", new DashboardOptions(), storage1);
}
工作正常.但是问题是我想基于用户使用UI选择的数据库连接字符串配置hangfire (用户将从下拉列表中选择数据库连接字符串).
It is working fine. but the problem is I want to configure the hangfire based on the databaseconnectionstring selected by user using UI(User will select databaseconnectionstring from dropdown).
问题:-
- 是否可以在控制器内部配置hangfire?怎么样?
- 我们可以在控制器内部传递 IApplicationBuilder 吗?(如在Startup.cs中一样配置hangfire)
- 使用中间件可以执行此操作吗?怎么样?
- 还有其他方法吗?
- Is it possible to configure the hangfire inside controller? How?
- Can we pass IApplicationBuilder inside controller?(To configure the hangfire as did in Startup.cs)
- Using middleware can I do this? How?
- Is there any other way to do this?
您可以通过将 JobStorage
设置为自定义实现来使用IoC
You can do this with IoC by setting JobStorage
to your custom implementation
services.AddScoped<JobStorage>(x =>
{
// resolve your storage, from IHttpContextAccessor or some other way
return new SqlServerStorage(...);
});
services.AddScoped<IBackgroundJobClient>(x => new BackgroundJobClient(
x.GetRequiredService<JobStorage>(),
x.GetRequiredService<IBackgroundJobFactory>(),
x.GetRequiredService<IBackgroundJobStateChanger>()));
这意味着 JobStorage
和 IBackgroundJobClient
现在已确定范围并针对每个请求进行了解析.这只是一个想法,您可能需要做一些更多的配置才能使您的案子正常工作.
This would mean that JobStorage
and IBackgroundJobClient
are now Scoped and resolved on each request. This is just an idea, you'll probably need to do some more configuration that's required for your case to work.