c# - 将接口传递给 Startup.cs ConfigureServices 中的另一个服务
问题描述
我需要在另一个服务的构造函数中传递一个接口作为参数。
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
有一个接受 a 的重载Func<IServiceProvider, TImplementation>
。
您可以使用IServiceProvider
检索注册的依赖项,使用GetRequiredService
:
services.AddSingleton<IAuthService>(sp =>
new MSAuthService(
MyConfigurationManager.GetJWTSecretKey(),
MyConfigurationManager.GetJWTLifespan(),
sp.GetRequiredService<IUserService>()
)
);
推荐阅读
- html - Bootstrap 导航栏过渡不平滑
- javascript - https://api.coingecko.com 的请求失败,返回代码 429。截断的服务器响应:错误代码:1015
- local-storage - LocalStorage 对于重要数据(例如(加密的)加密私钥)的可靠性如何?
- laravel - How can update laravel 5.5 to laravel 8 without changing blade,route and auth
- php - 如何将 JSON 传递给 Twig?
- python-packaging - Poetry 构建的包缺少运行时依赖项
- deno - 如何使用 denodb 执行“where”查询?
- sql - 在 PostgreSQL 问题中调用函数
- rust - 在特质 impl 中理解自我
- javascript - 如何检查缓存中是否已存在音频原型?