14

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();
    }
9
  • would it be worthwhile downloading the sample [github.com/aspnet/Docs/blob/master/aspnetcore/performance/… and comparing to your code? Commented Dec 5, 2018 at 3:55
  • 1
    can you check your *.csproj xml file for refs for any ref to IDistributedCache that you may need to clear out if it was previously added Commented Dec 5, 2018 at 3:57
  • @JohnB I am getting a 404 on that link. Commented Dec 5, 2018 at 3:59
  • Can you please publish Program.cs and Startup.cs Commented Dec 5, 2018 at 4:04
  • @VolodymyrBilyachat Please see my updated question. Commented Dec 5, 2018 at 4:26

3 Answers 3

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is great as even chatgpt failed to remove error after many hours which is resolved by just this suggestion. Thanks.
4

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

4 Comments

As i have mentioned in the question, I am not using (at least knowingly) IDistributedCache (services.AddDistributedMemoryCache()). I am using services.AddMemoryCache().
@JamesPoulose its not about what you add to services, something somewhere wants to inject distributed cache.
Removing app.UseSession() from Configure method was the key - thanks!
services.AddDistributedMemoryCache() and services.AddMemoryCache() worked for me
0

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.

Comments

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.