首页 > 解决方案 > 将接口传递给 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(具体)类作为参数传递。

标签: c#.netasp.net-core.net-core

解决方案


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

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

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

推荐阅读