3
その非常に簡単:Asp.Netコア:あなたが追加するには、起動中のコントローラ</p> <p>からあなたのメモリキャッシュにアクセスするASP.NETコアで使用メモリキャッシュコントローラ外部
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
}
してからからコントローラ
[Route("api/[controller]")]
public class MyExampleController : Controller
{
private IMemoryCache _cache;
public MyExampleController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
[HttpGet("{id}", Name = "DoStuff")]
public string Get(string id)
{
var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1));
_cache.Set("key", "value", cacheEntryOptions);
}
}
しかし、コントローラの外にある同じメモリキャッシュにどのようにアクセスできますか。例えば。私は、HangFireによって開始されるスケジュールされたタスクを持っています.HandFireのスケジュールされたタスクを介して起動する私のコード内からmemorycacheにアクセスするにはどうすればいいですか?
おかげで、これはあなたが
ConfigureServices
方法でScheduledStuff
インスタンスを設定する必要があることを意味します。問題は今、どのようにRunScheduledTasksメソッドを起動できますか? memoryCacheパラメータが必要です。ここでエラー 'scheduledStuff.RunScheduledTasks( - ' <;エラー\t CS7036 \tは、必要な仮パラメータの 'memoryCache' 'ScheduledStuff.ScheduledStuff(IMemoryCache') 'ScheduledStuff scheduledStuff =新しいScheduledStuff()に対応して与えられた引数はありません); ' – SpeedBird527あなたのコードに' SheduledStuff'インスタンスを作成するのではなく、これをDIコンテナから取得する必要があります。これをControllerやHttpContext.RequestServicesで依存関係として定義する必要があります。 –