My ConfigureServices section of Startup.cs
looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = services.AddIdentityServer()
.AddInMemoryApiResources(Configurations.ApiResources.GetApiResources())
.AddInMemoryClients(Configurations.Clients.GetClients());
services.AddEntityFrameworkNpgsql();
services.AddDbContext<IdentityDbContext>();
services.BuildServiceProvider();
services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
// Login Service and User Repo Injection
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<ILoginService, LoginService>();
// Connection String Config
services.Configure<ConnectionStringConfig>(Configuration.GetSection("ConnectionStringConfig"));
if (Environment.IsDevelopment())
{
builder.AddDeveloperSigningCredential();
}
}
I am injecting my loginService into ResourceOwnerPasswordValidator
, and I am injecting userRepository into my loginService. ResourceOwnerPasswordValidator
is handling the validation of my user's login.
I originally added my repository and loginService as singletons but I got the error
unable to consume scoped instance of DbContext from singleton userRepository.
As you can see above I changed both my loginService and userRepository instances to transient. Is this a safe way to do it, or is there another way I should choose?
My loginService uses userRepository to talk to the database. However if I add them as singletons,
I get a cannot consume scoped db instance
, so I thought I'd make the whole thing transient.
Is there a better way to do this which would allow me to keep loginService and userRepository as singletons?