6

I am trying to learn more about ASP.NET 5 and new .NET Core and trying to figure out if there is a built-in memory cache.

I have found out about Microsoft.Framework.Caching.Memory.MemoryCache. However there is very little documentation available.

Any help would be appreciated.

2 Answers 2

15

There are two caching interfaces, IMemoryCache and IDistributedCache. The IDistrbutedCache is intended to be used in cloud hosted scenarios where there is a shared cache, which is shared between multiple instances of the application. Use the IMemoryCache otherwise.

You can add them in your startup by calling the method below:

private static void ConfigureCaching(IServiceCollection services)
{
    // Adds a default in-memory implementation of IDistributedCache, which is very fast but 
    // the cache will not be shared between instances of the application. 
    // Also adds IMemoryCache.
    services.AddCaching();

    // Uncomment the following line to use the Redis implementation of      
    // IDistributedCache. This will override any previously registered IDistributedCache 
    // service. Redis is a very fast cache provider and the recommended distributed cache 
    // provider.
    // services.AddTransient<IDistributedCache, RedisCache>();

    // Uncomment the following line to use the Microsoft SQL Server implementation of 
    // IDistributedCache. Note that this would require setting up the session state database.
    // Redis is the preferred cache implementation but you can use SQL Server if you don't 
    // have an alternative.
    // services.AddSqlServerCache(o =>
    // {
    //     o.ConnectionString = 
    //       "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";
    //     o.SchemaName = "dbo";
    //     o.TableName = "Sessions";
    // });
}

The IDistributedCache is the one most people will want to use to get the most out of caching but it has a very primitive interface (You can only get/save byte arrays with it) and few extension methods. See this issue for more information.

You can now inject either IDistributedCache or IMemoryCache into your controller or service and use them as normal. Using them is pretty simple, they are a bit like dictionaries after all. Here is an example of the IMemoryCache:

public class MyService : IMyService
{
    private readonly IDatabase database;
    private readonly IMemoryCache memoryCache;

    public MyService(IDatabase database, IMemoryCache memoryCache)
    {
        this.database = database;
        this.memoryCache = memoryCache;
    }

    public string GetCachedObject()
    {
        string cachedObject;
        if (!this.memoryCache.TryGetValue("Key", out cachedObject))
        {
            cachedObject = this.database.GetObject();
            this.memoryCache.Set(
                "Key", 
                cachedObject, 
                new MemoryCacheEntryOptions()
                {
                    SlidingExpiration = TimeSpan.FromHours(1)
                });
        }

        return cachedObject;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is very helpful, but I am not that interested about Database cache. To me it is useless. If the data is already stored in DB and I am paying the high cost to access it, what's the point of caching it in DB!
I agree, don't use SQL Server. Using the memory cache is the fastest option but what if you have multiple instances of your site? This is where Redis cache comes in. Redis is very fast and for just these purposes. If you use IDistributedCache, then if you want another instance of your site due to lots of users its easy to do, your site becomes scalable.
SQL Server 2016 now also has an In-Memory mode, so it's a lot faster and now a viable caching option.
3

Here's a MemoryCache sample: https://github.com/aspnet/Caching/tree/dev/samples/MemoryCacheSample

More samples: https://github.com/aspnet/Caching/tree/dev/samples

1 Comment

These samples are all console apps. I don't think that's what @sam360 was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.