起動時に、私は自分のWebアプリケーション用の静的データのストアを作成したいと思います。だから私は最終的にMicrosoft.Extensions.Caching.Memory.MemoryCacheに遭遇した。 MemoryCacheを使用する機能を構築した後、私は突然、私が格納したデータが利用できないことを知る。したがって、おそらく2つの別々のインスタンスになります。起動時にMemoryCacheにデータを保存するにはどうすればよいですか?
他のWebアプリケーションで使用される起動時のMemoryCacheインスタンスにはどうすればアクセスできますか?これは、私は現在、それをしようとしている方法です:
public class Startup
{
public Startup(IHostingEnvironment env)
{
//Startup stuff
}
public void ConfigureServices(IServiceCollection services)
{
//configure other services
services.AddMemoryCache();
var cache = new MemoryCache(new MemoryCacheOptions());
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
//Some examples of me putting data in the cache
cache.Set("entryA", "data1", entryOptions);
cache.Set("entryB", data2, entryOptions);
cache.Set("entryC", data3.Keys.ToList(), entryOptions);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//pipeline configuration
}
}
そして、これが不可能な場合は、私がMemoryCache
public class ExampleController : Controller
{
private readonly IMemoryCache _cache;
public ExampleController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet]
public IActionResult Index()
{
//At this point, I have a different MemoryCache instance.
ViewData["CachedData"] = _cache.Get("entryA");
return View();
}
}
を使用するコントローラは、そこには、おそらくより良い/より簡単な代替手段ですか?グローバルシングルトンはこのような状況で動作しますか?