Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.1 - Error Implementing MemoryCache

I was following the steps given here to implement a MemoryCache in ASP.NET Core and when i start the application (dotnet run from command prompt), i get the following error.

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.

What is confusing me is that i am using services.AddMemoryCache() and NOT services.AddDistributedMemoryCache(). Full stack trace is available in this bin. I have only these packages referenced

<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />

My Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();
    app.UseSpaStaticFiles();
    app.UseSession();
    app.UseCors(
        builder => builder
            .WithOrigins("http://localhost:4200")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            .AllowCredentials());
    app.UseMvc(
        routes =>
        {
            routes.MapRoute(
                "default",
                "api/{controller}/{action}/{id?}");
        });
}

ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services
        .AddMvcCore()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonFormatters();

    services.AddMemoryCache();

    // Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; });
    services.AddSession(
        options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromHours(1);
            options.Cookie.HttpOnly = true;
        });
}

Program.cs

  public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
    }

    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }
like image 699
James Poulose Avatar asked Dec 05 '18 03:12

James Poulose


People also ask

How do I use MemoryCache in .NET Core?

ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache.

How do I check MemoryCache?

Right-click on the Start button and click on Task Manager. 2. On the Task Manager screen, click on the Performance tab > click on CPU in the left pane. In the right-pane, you will see L1, L2 and L3 Cache sizes listed under “Virtualization” section.

Where is MemoryCache stored?

Memory caching (often simply referred to as caching) is a technique in which computer applications temporarily store data in a computer's main memory (i.e., random access memory, or RAM) to enable fast retrievals of that data. The RAM that is used for the temporary storage is known as the cache.

Is MemoryCache a singleton?

Note that the MemoryCache is a singleton, but within the process. It is not (yet) a DistributedCache. Also note that Caching is Complex(tm) and that thousands of pages have been written about caching by smart people.


2 Answers

Seems to be that you try to inject IDistributedCache which is different from memory cache. Distributed cache will be using external services to store cache while memory cache is going to use servers memory.

As I said something,somewhere is using distributed cache. And that something is session

From that page

The default session provider in ASP.NET Core loads session records from the underlying IDistributedCache

like image 105
Vova Bilyachat Avatar answered Sep 23 '22 22:09

Vova Bilyachat


Simply adding services.AddMemoryCache() after services.AddControllers() worked for me.

like image 24
Jhonnatan Panoch Avatar answered Sep 25 '22 22:09

Jhonnatan Panoch