Search code examples
c#asp.net-core

Passing parameters to a service that already has dependency injection


I have a service with the following constructor

public TokenService(UserManager<IdentityUser> userManager, ApplicationDbContext dbContext)
{
    _userManager = userManager;
    _dbContext = dbContext;
}

In Startup.cs I have registered the service :

services.AddScoped<TokenService>();

I would like to add a string parameter to the constructor and pass the string to the service where I register the service in Startup.cs

I know you can pass parameters by creating a new instance during registration but I don't know how to pass the UserManger and ApplicationDbContext objects when doing it manually.

If I do this :

services.AddScoped<>(_ => new TokenService(null , null, "secret");

it doesn't work with the dependency injection of the other services.

As a workaround, I have added the string with a method in Program.cs but would like to remove this.


Solution

  • Normally when you want to provide parameters to something that also needs to get dependencies injected you end up creating a factory. However in this case since the parameters are known during registration you can easily fix this registering a factory method directly:

    services.AddSingleton(serviceProvider => new TokenService(serviceProvider.GetRequiredService<UserManager<IdentityUser>>(), serviceProvider.GetRequiredService<ApplicationDbContext>(), "hello"));
    

    In you comments you state that this can't be a singleton, that doesn't matter with the factory method, just as easy to register a transient for example:

    services.AddTransient(serviceProvider => new TokenService(serviceProvider.GetRequiredService<UserManager<IdentityUser>>() , serviceProvider.GetRequiredService<ApplicationDbContext>(), "hello"));
    

    Hopes this helps