具体来说,我正在查看Microsoft.Extension.DependencyInjection.ServiceCollectionServiceExtension.cs:中的这行代码
public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class;
使用这种方法的一个例子是:
services.AddScoped<ICustomService>(sp => new CustomService(
sp.GetRequiredService<IAnotherCustomService>(), "Param1", "Param2"));
我理解Func委托和lambda表达式是如何工作的,但我不理解IServiceProvider
是如何在幕后初始化的。
IServiceProvider
此时未在后台初始化。该框架只是捕获传入的委托,并将其保存以备以后使用,此时它具有IServiceProvider实例并需要生成ICustomService
。
这里没有任何特定于接口的内容。同样的原则也适用于委托的任何参数类型。
// 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);