在我的脑海中,您可以尝试将 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 和类型化客户端的 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,然后在 UseFilter 调用中使用 IServiceProvider 解决它
// 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 解决方案不像我最初建议的那样工作。