Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading