gpt4 book ai didi

c# - 将接口(interface)传递给 Startup.cs ConfigureServices 中的另一个服务

转载 作者:行者123 更新时间:2023-12-02 19:35:05 24 4
gpt4 key购买 nike

我需要将接口(interface)作为参数传递到另一个服务的构造函数中。

MSAuthService 构造函数需要 3 个参数:

public MSAuthService(string jwtSecret, int jwtLifespan, IUserService userService)
{
this._jwtSecret = jwtSecret;
this._jwtLifespan = jwtLifespan;
this._userService = userService;
}

启动.cs:

services.AddScoped<IUserService, UserManager>();
....
services.AddSingleton<IAuthService>(
new MSAuthService(
MyConfigurationManager.GetJWTSecretKey(),
MyConfigurationManager.GetJWTLifespan(),
// I want to pass IUserService as parameter here
)
);

我不知道如何将 IUserService 传递给 MSAuthService 的构造函数。我不想将 UserManager (具体)类作为参数传递。

最佳答案

AddSingleton有一个接受 Func<IServiceProvider, TImplementation> 的重载.

您可以使用IServiceProvider要检索已注册的依赖项,请使用 GetRequiredService :

services.AddSingleton<IAuthService>(sp =>
new MSAuthService(
MyConfigurationManager.GetJWTSecretKey(),
MyConfigurationManager.GetJWTLifespan(),
sp.GetRequiredService<IUserService>()
)
);

关于c# - 将接口(interface)传递给 Startup.cs ConfigureServices 中的另一个服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61177490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com