我们正在将Hangfire用于一些夜间和长期运行的工作,我们正在单独的数据库中跟踪每个作业的其他相关详细信息/元数据,以避免将来出现Hangfire升级问题。作业过滤器(https://docs.hangfire.io/en/latest/extensibility/using-job-filters.html)可以帮助我们以更简单的方式跟踪每个作业的状态,但是我找不到如何将依赖项发送到作业过滤器的示例。
我们正在运行带有依赖注入(DI)的ASP.NET Core和存储库+工作模式单元。
如何从作业过滤器中访问数据库上下文(或工作单元或通过DI可用的任何其他项目)?
谢谢
编辑我已经创建了一个包含一个小样本项目的存储库,该项目概述了我在这里要做的事情:https://github.com/joelpereira/hfjobfilter/tree/master/HFJobFilter
它编译但在行上有错误:.UseFilter(new TypeFilterAttribute(typeof(LogToDbAttribute)))
从我的头脑中,您可以尝试将JobFilter添加为TypeFilter,它将自动注入LogEverythingAttribute
的构造函数中的依赖项(如果有),因此从您提供的链接修改示例:
public class EmailService
{
[TypeFilter(typeof(LogEverything))]
public static void Send() { }
}
GlobalJobFilters.Filters.Add(new TypeFilterAttribute(typeof(LogEverythingAttribute())));
免责声明:我自己没有测试过上述内容,如果有效,请告诉我。
编辑
尝试在ConfigureServices
中配置如下所示的Hangfire,看看是否有效
services.AddHangfire(config =>
{
config.UseFilter(new TypeFilterAttribute(typeof(LogToDbAttribute)));
// if you are using the sqlserverstorage, uncomment the line and provie
// the required prameters
// config.UseSqlServerStorage(connectionString, sqlServerStorageOptions);
});
更新的答案
请查看我对您提供的代码所做的changes。我测试了它,它正在工作。下面几点要注意。
请查看我如何使用利用HttpClientFactory和Typed Clients的AddHttpClient方法注册HttpClient。这是使用HttpClient的推荐方法。你可以阅读更多关于它here
services.AddHttpClient<HfHttpClient>(client =>
{
client.BaseAddress = new Uri("http://localhost:44303");
// you can set other options for HttpClient as well, such as
//client.DefaultRequestHeaders;
//client.Timeout
//...
});
此外,您需要注册LogDbAttribute
,然后使用IServiceProvider
在UseFilter调用中解析它
// register the LogToDbAttribute
services.AddSingleton<LogToDbAttribute>();
// build the service provider to inject the dependencies in LogDbAttribute
var serviceProvider = services.BuildServiceProvider();
services.AddHangfire(config => config
.UseSqlServerStorage(Configuration.GetConnectionString("HangfireDBConnection"))
.UseFilter(serviceProvider.GetRequiredService<LogToDbAttribute>()));
我还注入了ILogger来证明它正在工作。出于某种原因,如果您尝试使用HttpClient做任何事情,它会挂起。也许,原因是它是一个后台工作,所有HttpClient调用都是异步的,所以它不会回来,两个进程试图互相等待。
如果您打算注入HttpClient,您可能需要查看它。但是,记录器工作正常。
此外,您不需要从TypeFilterAttribute继承LogDbAttribute。 TypeFilterAttribute解决方案不像我最初建议的那样工作。