0

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?

Naveen
  • 1,441
  • 2
  • 16
  • 41
Pointo Senshi
  • 541
  • 5
  • 17

1 Answers1

3

Typically you'd only want to use a singleton in a web application if any of the following is true and if the class in question is thread-safe:

  • Construction of an underlying resource (e.g. a connection to a distributed cache) is expensive
  • You need to maintain in-memory state for the duration of the application
  • You need to serialize access to a resource (e.g. an append-only file)

In your case none of these are true so scoped or transient are totally fine.

mackie
  • 4,996
  • 1
  • 17
  • 17