2016-11-30 8 views
3

起動時に、私は自分の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(); 
    } 
} 

を使用するコントローラは、そこには、おそらくより良い/より簡単な代替手段ですか?グローバルシングルトンはこのような状況で動作しますか?

答えて

6

あなたのコントローラでやったように。新しいメモリキャッシュを作成する代わりに、作成したシングルトンオブジェクトに値を追加する必要があります。これを行うには、Configureメソッドを次のように変更します。

public void Configure(IApplicationBuilder app, 
     IHostingEnvironment env, 
     ILoggerFactory loggerFactory, 
     IMemoryCache cache) 
{ 
    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); 
    //pipeline configuration 
} 
1

使用Configure方法、ないConfigureServices:あなたは声明

services.AddMemoryCache(); 

、あなたがIMemoryCacheを注入しどこ解決になるだろうメモリキャッシュのシングルトンを望んでいたと言って有効であったが追加

public void Configure(IApplicationBuilder app, IMemoryCache cache, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    cache.Set(...); 
} 
関連する問題