Skip to content

Add extension method to help set DI injectable MemoryCache with enabled statistics tracking ability #67769

@maryamariyan

Description

@maryamariyan

With #50406, we added IMemoryCache.GetCurrentStatistics() API, which helps us track statistics such as cache hits, misses, cache count and size for IMemoryCache. This capability is turned off by default.

The new GetCurrentStatistics() API allows app developers to use either event counters or metrics APIs to track statistics with code snippets illustrated in this gist.

In this issue we would want to add an extension method using ServiceCollection to add a MemoryCache with statistics tracking enabled.

namespace Microsoft.Extensions.DependencyInjection
{
    public static partial class MemoryCacheServiceCollectionExtensions
    {
         public IServiceCollection AddDistributedMemoryCache(this IServiceCollection services, Action<MemoryDistributedCacheOptions> setupAction) { }
         public static IServiceCollection AddMemoryCache(this IServiceCollection services) { }
         public static IServiceCollection AddMemoryCache(this IServiceCollection services, Action<MemoryCacheOptions> setupAction) { }
+        public static IServiceCollection AddStatisticsTrackingMemoryCache(this IServiceCollection services) { }
     }
}

Alternative design

We could make the default behaviour for both existing AddMemoryCache API overloads to always configure MemoryCacheOptions with TrackStatistics set to enabled by default:

AddMemoryCache(this IServiceCollection services)
{
    services.AddOptions();
    services.TryAdd(ServiceDesciptor.Singleon<IMemoryCache, MemoryCache>());
    services.Configure(opt => { opt.TrackStatistics=true; });
    // when a Name API is available we'd also set a default name for this cache
    return services;
}

Benefit with this design it that it helps take zero code changes/no rebuild/no redeploy for devs to get stats on the cache created by AddMemoryCache() in dotnet-counters.

The downside of this alternative design is that it adds an element of surprise to the AddMemoryCache API for those who assumed it should configure default MemoryCacheOptions, by default setting TrackStatistics bool flag to false.

There is prior precedence in extensions libraries, e.g. with AddConsole and AddSimpleConsole/AddJsonConsole etc. where AddConsole configures options with default value but e.g. AddSimpleConsole would configure similarly but also set formatter name to simple.

Goal

This issue is part of multi step process to provide a great user experience for tracking statistics for memory cache.

For more information refer to #66479 (comment)

cc @noahfalk @davidfowl

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions