Search code examples
c#.netdependency-injection.net-8.0

AddKeyedScoped initializing object with func<IServiceProvider, object?, TService> implementationFactory not working? .NET 8


I have started using AddKeyedScoped with .NET 8.

I want use my own initialization object for dependency:

public static IServiceCollection AddKeyedScoped<TService>(
    this IServiceCollection services,
    object? serviceKey,
    Func<IServiceProvider, object?, TService> implementationFactory)
    where TService : class
{
    ThrowHelper.ThrowIfNull(services);
    ThrowHelper.ThrowIfNull(implementationFactory);

    return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
}

Has anyone used above implementation for setting key with initialization?

 services.AddScoped<Imyinterface>(s =>
     new SqlConnectionFactory(new myimplementation()));

For scope this work fine, but for AddKeyedScoped

services.AddKeyedScoped<Imyinterface>("mykey", rec => new myimplementation()})

this code is not working. Has anyone tried AddKeyedScoped with initial value in .NET 8?


Solution

  • As you can see from the AddKeyedScoped signature it accepts factory with 2 parameters - Func<IServiceProvider, object?, TService> implementationFactory, one is service provider and another - key, so you need to pass corresponding lambda:

    services.AddKeyedScoped<IMyInterface>("mykey", (sp, key) => new MyImplementation());