HttpContext and Caching in .NET Core >= 1.0

The in memory cache functionality is still there, it has just been moved around a bit. If you add

"Microsoft.Extensions.Caching.Memory": "1.1.0"

to you project.json file and the add

        services.AddMemoryCache();

to you Startup.ConfigureServices method, you'll have set up a singleton memory cache instance that works pretty much like the old one did. You get to it via dependency injection so a controller with a constructor can get a instance.

public class HomeController: Controller 
{
    private IMemoryCache _cache;
    public HomeController(IMemoryCache cache) 
    {
        _cache = cache;
    }

}

You can then use _cache in the class above to get to the globally available singleton class. There are other sorts of caches that you might want look at as well, including a Redis cache for out of process storage.


You should use the In Memory Cache only as HttpContext cache object was actually appdomain cache object although it is exposed using the HttpContext

From the msdn https://msdn.microsoft.com/en-us/library/system.web.httpcontext.cache(v=vs.110).aspx

There is one instance of the Cache class per application domain. As a result, the Cache object that is returned by the Cache property is the Cache object for all requests in the application domain.

We should use the

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using System;
using Microsoft.Extensions.FileProviders;

namespace CachingQuestion
{
public class Startup
{
    static string CACHE_KEY = "CacheKey";

    public void ConfigureServices(IServiceCollection services)
    {
        //enabling the in memory cache 
        services.AddMemoryCache();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var fileProvider = new PhysicalFileProvider(env.ContentRootPath);

        app.Run(async context =>
        {
            //getting the cache object here
            var cache = context.RequestServices.GetService<IMemoryCache>();
            var greeting = cache.Get(CACHE_KEY) as string;


        });
    }
}

 public class Program
 {
    public static void Main(string[] args)
    {
          var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}
}