Using the Clean Architecture template for a .NET application, when setting up the DbContext, it adds a scoped service by default. So why is there a need to add an additional line for scope. Does this provide additional functionality?
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IApplicationDbContext>(provider =>
provider.GetService<ApplicationDbContext>());
}
CodePudding user response:
The 2nd line register the interface on the dependency injection container. It adds the possibility to inject the interface instead of the concrete implementation.
The reason AddScoped is used, is that AddDbContext also uses a request scoped instance. And the reason that a request scoped instance is used instead of a singleton is that DbContext is not thread-safe, so the same instance should not be re-used across threads.