Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access cache in ASP.NET 5 MVC?

Tags:

asp.net-core

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.

like image 815
sam360 Avatar asked Jul 24 '15 03:07

sam360


People also ask

How can use cache in ASP.NET MVC?

In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.

How can store data in cache in ASP.NET MVC?

Store data into Cache in ASP.NET MVC in ASP.NET MVC Above action method first checks for the null value in HttpContext. Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag. DateTime.

How output cache works in MVC?

The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.

Where is ASP.NET cache stored?

The cached data is stored in server memory. Class Caching : Web pages or web services are compiled into a page class in the assembly, when run for the first time. Then the assembly is cached in the server.


2 Answers

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;
    }
}
like image 162
Muhammad Rehan Saeed Avatar answered Oct 09 '22 19:10

Muhammad Rehan Saeed


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

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

like image 21
Victor Hurdugaci Avatar answered Oct 09 '22 18:10

Victor Hurdugaci