[英]How To Get Configurable Cache Duration on Service Methods With ServiceStack?
我在服務中的一種 Get 方法上使用了CacheResponseAttribute
,例如[CacheResponse(Duration = 60)]
。 但我希望此緩存持續時間來自配置文件,因此我可以根據服務當前運行的環境(開發、產品等)將其設置為不同
我知道我們不能在屬性構造函數中使用非常量作為參數。 所以我打算做類似的事情
public class MyCacheResponseAttribute : CacheResponseAttribute
{
public IConfiguration Configuration { get; set; }
public CacheWidgetResponseAttribute()
{
int.TryParse(Configuration["cache_duration_in_secs"], out var cacheDuration);
Duration = cacheDuration;
}
}
並將其用作 Get 方法的裝飾器。 但是,依賴注入似乎不適用於屬性,因為我將配置設置為 null。
我的返回類型是字符串,我試過 ToOptimizedResultUsingCache 但我無法讓它正確返回字符串。
我有什么選擇? 是否有可能使 IoC 以某種方式在屬性上工作? 我想作為最后的手段,我可以在服務中使用ICacheClient
並使用它,但這將是我最后的手段,因為它會更加定制。
請求過濾器屬性確實具有從 IOC 自動裝配的屬性,但這只能在執行對象構造函數之后發生,而不是之前。
因此,您可以在執行屬性之前從注入的 IOC 屬性中讀取數據,例如:
public class MyCacheResponseAttribute : CacheResponseAttribute
{
public IConfiguration Configuration { get; set; }
public override Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
{
if (Duration == default
&& int.TryParse(Configuration["cache_duration_in_secs"], out var duration))
Duration = duration;
return base.ExecuteAsync(req, res, requestDto);
}
}
或者通過 singleton 解決 IOC 依賴關系,例如:
public class MyCacheResponseAttribute : CacheResponseAttribute
{
public MyCacheResponseAttribute()
{
var config = HostContext.Resolve<IConfiguration>();
if (int.TryParse(config["cache_duration_in_secs"], out var duration))
Duration = duration;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.