Friday, May 8, 2020

get IMemoryCache to work with Autofac

In the setup...

builder.RegisterType<MemoryCache>().As<IMemoryCache>().SingleInstance();

 
 

At a Controller...

private readonly IMemoryCache _memoryCache;
public ServiceController(IMemoryCache memoryCache)
{
   _memoryCache = memoryCache;

 
 

In an action...

var cacheEntry = _memoryCache.GetOrCreate("foo", entry =>
{
   entry.Value = (object)"bar";
   return Task.FromResult((string) entry.Value);
});

 
 

Elsewhere, in a different action...

object cacheEntry = _memoryCache.Get("foo");

No comments:

Post a Comment