Skip to content

SizeLimit support for Microsoft.Extensions.Caching.Memory #237

@MichaCo

Description

@MichaCo

In version 2.x, Microsoft added a SizeLimit option to the MemoryCacheOptions and implemented a new eviction logic based off of that.
If SizeLimit is set, each CacheEntry added to the MemoryCache has to have it's Size property defined.

Right now, CacheManager doesn't set Size of each CacheEntry´ because it obviously cannot predict or calculate the actual size (same reason why Microsoft did that change and remove the MemoryPressure based eviction). But that mean, if you configure SizeLimit` right now, you'll get the following hard exception:

Unhandled Exception: System.InvalidOperationException: Cache entry must specify a value for Size when SizeLimit is set.
   at Microsoft.Extensions.Caching.Memory.MemoryCache.SetEntry(CacheEntry entry)

To support SizeLimit for the Microsoft.Extensions.Caching cache handle, I came up with the following options:

  • Hard validation error while configuring the cache, so that it doesn't throw later in app code... This doesn't really support the setting, but at least prevents issues
  • Add a configuration setting to always set each CacheEntry to a certain size. This is ok if each cached object has the same size, but isn't really sufficient for advanced scenarios. Or even simple scenario where an object contains a list of objects and the size is basically list.Count * sizePerItem...
  • Add a factory to the configuration of this cache handle which allows users to set the size for each key, whenever a key gets added. This will be some more work.

If anyone has a better idea, let me know ;)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions