当需要接口作为参数时,Func 委托如何工作?
How does the Func delegate work when it requires an interface as a parameter?
具体来说,我正在查看来自 Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.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
此时未在幕后进行初始化。该框架只是捕获 passed-in 委托并将其保存以备后用,当它有一个 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);
具体来说,我正在查看来自 Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.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
此时未在幕后进行初始化。该框架只是捕获 passed-in 委托并将其保存以备后用,当它有一个 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);