c# - Flushing MemoryCache ASP.NET Core 2 -


i trying flush cache after update item, , have tried few different options , none working expected

public class postapicontroller : controller {     private readonly ipostservice _postservice;     private readonly iposttagservice _posttagservice;     private imemorycache _cache;     private memorycacheentryoptions cacheentryoptions;     public postapicontroller(ipostservice postservice, iposttagservice posttagservice, imemorycache cache)     {        _postservice = postservice;        _posttagservice = posttagservice;        _cache = cache;        cacheentryoptions = new memorycacheentryoptions()           .setslidingexpiration(timespan.fromdays(1));     }      [httpget("{url}", name = "getpost")]     public iactionresult getbyid(string url, bool includeexcerpt)      {        post cacheentry;        if (!_cache.trygetvalue($"getbyid{url}{includeexcerpt}", out cacheentry))        {          cacheentry = _postservice.getbyurl(url, includeexcerpt);         _cache.set($"getbyid{url}{includeexcerpt}", cacheentry, cacheentryoptions);       }        if (cacheentry == null)       {         return notfound();       }        return new objectresult(cacheentry);     }      [httpput("{id}")]     public iactionresult update(int id, [frombody] post item)     {       if (item == null)       {          return badrequest();        }        var todo = _postservice.getbyid(id);       if (todo == null)       {          return notfound();       }         _postservice.update(item);        _posttagservice.sync(item.tags.select(a => new posttag { postid = item.id, tagid = a.id }).tolist());        //want flush entire cache here        return new nocontentresult();      } 

i have tried dispose() memorycache here on next api call, still disposed. since keys dynamic, can't keys. how can go doing this?

you can store dictionary instead. way can use dynamic keys entries , 1 single static key dictionary container, can stored in cache instead of storing each entry separately.

something that:

private const string cachedentrieskey = "some-static-key";  [httpget("{url}", name = "getpost")] public iactionresult getbyid(string url, bool includeexcerpt) {     dictionary<string, post> cacheentries;     if (!_cache.trygetvalue(cachedentrieskey, out cacheentries))     {         cacheentries = new dictionary<string, post>();         _cache.set(cachedentrieskey, cacheentries);     }      var entrykey = $"getbyid{url}{includeexcerpt}";     if (!cacheentries.containskey(entrykey))     {         return notfound(); // way, why instead of adding cache?     }      return new objectresult(cacheentries[entrykey]); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -