1 回答

TA貢獻1811條經驗 獲得超4個贊
從我的頭頂開始,您可以嘗試將 JobFilter 添加為TypeFilter,它會自動注入依賴項(如果您的構造函數中有依賴項)LogEverythingAttribute,因此請修改您提供的鏈接中的示例:
public class EmailService
{
[TypeFilter(typeof(LogEverything))]
public static void Send() { }
}
GlobalJobFilters.Filters.Add(new TypeFilterAttribute(typeof(LogEverythingAttribute())));
免責聲明:我自己沒有測試過以上內容,所以請告訴我是否可行。
已編輯
嘗試像下面這樣配置 Hangfire ConfigureServices,看看是否可行
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);
});
更新的答案
請查看我對您提供的代碼所做的更改。我已經對其進行了測試并且可以正常工作。下面幾點需要注意。
請查看我是如何使用利用 HttpClientFactory 和類型化客戶端的 AddHttpClient 方法注冊 HttpClient 的。這是使用 HttpClient 的推薦方式。你可以在這里閱讀更多相關信息
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 解決方案并不像我最初建議的那樣工作。
- 1 回答
- 0 關注
- 78 瀏覽
添加回答
舉報