Cannot access disposed object MemoryCache

113 Views Asked by At

I'm trying to use IMemoryCache in Minimal API actions in .NET 8 like this:

public static async Task<Results<Accepted, ProblemHttpResult>> GetUpdates(
    [FromServices] IMemoryCache memoryCache,
    HttpContext context)
{
    try
    {
        using var reader = new StreamReader(context.Request.Body);
        string updates = await reader.ReadToEndAsync();
        var list = // convert updates to list object

        memoryCache.Set("Updates", list);

        return TypedResults.Accepted("/");
    }
    catch (Exception ex)
    {
        return TypedResults.Problem(ex.Message);
    }
}

It was working fine before, changed DBContext from Singleton to Scoped due to some problems and after that I'm having this problem while trying to use memory cache.

Using IMemoryCache to store a list of objects and they'll be retrieved in AutoMapper mapping profile (that field needs to be updated frequently).

Tried using IMemoryCache as scoped, it didn't throw any errors but when getting IMemoryCache instance in mapping profile class, it doesn't contain anything.

1

There are 1 best solutions below

4
On

You say the problem started when you changed the dbcontext setup, but the code shown doesn't show a dbcontext. I therefore presume that this is used in the code marked convert updates to list object.

I'm guessing the problem here is that your list contains database objects that are connected to the dbcontext, perhaps using deferred loading; if a dbcontext-bound object is cached, it will outlive the dbcontext, and any delayed loads will fail with the symptom described. So: don't do that. Only cache simple POCO types that are entirely detached from any complex loading APIs. And ideally: immutable, so you can't get problems with competing requests changing the shared instance.