What is wrong?

In wonderful .NET Core we have a interface IMemoryCache that we can inject after configuring it with the following command:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    ...
}

After playing some time with given interface I have tried to add some entry to cache:

public class SomeService
{
    private readonly IMemoryCache memCache;

    public SomeService(IMemoryCache memCache) 
    {
        this.memCache = memCache;
    }

    
    public void Add(string key, string value)
    {
        this.memCache.CreateEntry(key).SetValue(value);
    }
}

I was very confused when turned out that it is not working… Get always returns null.

Solution….

… is very simple:

public class SomeService
{
    private readonly IMemoryCache memCache;

    public SomeService(IMemoryCache memCache) 
    {
        this.memCache = memCache;
    }

    
    public void Add(string key, string value)
    {
        this.memCache.Set(key, value);
    }
}

Yep, Set is extension method that works fine.

Why?

Do not know. Really, I can’t figure out why is that happening. Maybe you guys?


Patryk Wąsiewicz

A very casual blog about programmer's life.