Pass Interface to another service in Startup.cs ConfigureServices

Viewed 844

I need to pass an Interface as a parameter in another service's constructor.

MSAuthService constructor needs 3 parameters:

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

Startup.cs:

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

I couldn't figure out how to pass the IUserService to MSAuthService's constructor. I don't want to pass UserManager (concrete) class as a parameter.

2 Answers

AddSingleton has an overload that accepts a Func<IServiceProvider, TImplementation>.

You can use the IServiceProvider to retrieve the registered dependency, using GetRequiredService:

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

‍did you try to use this on Configure method?

var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope();
scope.ServiceProvider.GetService<IUserService>();
Related