Keyed Services in the IServiceProvider in .NET 8 preview 7

8/7/2023

The .NET 8 preview 7 will bring another exciting feature some of you probably awaiting for a long time: Keyed services.

Example

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<BigCacheConsumer>();
builder.Services.Addsingleton<SmallCacheConsumer>();

builder.Services.AddKeyedSingleton<IMemoryCache, BigCache>(“big“);
builder.Services.AddKeyedSingleton<IMemoryCache, SmallCache>("small“);

var app = builder.Build();

app.MapGet(“/big", (BigCacheConsumer data) => data.GetData());
app.MapGet(“/small", (SmallCacheConsumer data) => data.GetData());

app.Run();

class BigCacheConsumer([FromKeyedServices("big“)] IMemoryCache cache)
{
    public object? GetData() => cache.Get("data");
}

class SmallCacheConsumer(IServiceProvider keyedServiceProvider)
{
    public object? GetData() => keyedServiceProvider.GetRequiredKeyedService<IMemoryCache>("big");
}

The addition of new overloads like AddKeyedSingleton or AddKeyedScoped allow to pass in a named (keyed) service that can then be consumed with a new attribute in the dependent service.

Also, as shown in the SmallCacheConsumer, there is the option to retrieve them at runtime:

var keyedService = keyedServiceProvider.GetRequiredKeyedService<IService>("key");

So why would you need keyed services in the first place? There could be multiple scenarios, like: Multitenancy, feature toggles, or A/B testing.

MemoryCache, DistributedCache and HybridCache

The latest preview (.NET 9 preview 4) brought another caching structure to the .NET world - so let's order some things here.

ReadOnlySet<T> in .NET 9

The next preview (preview 6) will bring a new type ReadOnlySet<T>. This is a read-only set that is similar to ReadOnlyCollection<T>. Let's see how it works and why it was introduced.

.NET 8 Performance Edition

As with every .NET release, Microsoft improves the performance of the runtime and guess what: This release is no exception to this. In this blog post, I want to go through some of the improvements made so far (.NET 8 preview 3).

An error has occurred. This application may no longer respond until reloaded. Reload x