Home > OS >  How does the Func delegate work when it requires an interface as a parameter?
How does the Func delegate work when it requires an interface as a parameter?

Time:02-26

Specifically, I'm looking at this line of code from Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.cs:

public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class;

An example using this method would be:

services.AddScoped<ICustomService>(sp => new CustomService(
    sp.GetRequiredService<IAnotherCustomService>(), "Param1", "Param2"));

I understand how the Func delegate and lambda expressions work, but I'm not understanding how IServiceProvider is being initialized behind the scenes.

CodePudding user response:

IServiceProvider is not being initialized behind the scenes at this point in time. The framework is merely capturing the passed-in delegate and saving it for a later time, when it has an IServiceProvider instance and needs to generate an ICustomService.

There is nothing specific to interfaces happening here. The same principle would apply with any argument type for a delegate.

// This captures the delegate in a variable
Func<int, string> f = i => i.ToString();

// This invokes the delegate with an instance of an `int`
f(1);
f(2);
  • Related