简体   繁体   中英

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();
    }

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

The AddDistributedMemoryCache method adds an implementation of IDistributedCache that uses server memory for storage. It's not a distributed memory cache. The documentation for it says as much.

So, you can safely use it to resolve the error you're seeing without adverse effects. Or just don't use anything that requires an IDistributedCache, such as the UseSession method.

只需在 services.AddControllers() 为我工作之后添加 services.AddMemoryCache() 。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM