Skip to content

AddDbContext with ServiceLifetime.Scoped should pass scoped IServiceProvider to optionsAction #8797

Closed

Description

@prochnowc

When registering DbContext via AddDbContext(Action<IServiceProvider, DbContextOptionsBuilder>) with ServiceLifetime.Scoped i expect IServiceProvider argument passed to the optionsAction to be IServiceProvider from IServiceScope.

Unfortunately AddDbContext adds DbContextOptions as singleton. Should'nt DbContextOptions be also added scoped when using ServiceLifetime.Scoped ?

In my case i resolve many DbContext's which need to use same DbConnection provided by a scoped IDbConnectionProvider. This enables me to call SaveChanges on different contexts in same transaction.

Steps to reproduce

services.AddScoped<IDbConnectionProvider, DbConnectionProvider>();
services.AddDbContext<DbContextA>(o => (sp, o) => o.UseSqlServer(sp.GetRequiredService<IDbConnectionProvider>().GetConnection());
services.AddDbContext<DbContextB>(o => (sp, o) => o.UseSqlServer(sp.GetRequiredService<IDbConnectionProvider>().GetConnection());

sp argument in AddDbContext should be instance provided by IServiceScope.

Further technical details

EF Core version: 1.1.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017

Activity

  1. ajcvickers commented on Jun 9, 2017

    @ajcvickers
    Contributor

    @prochnowc DbContextOptions is intentionally registered as singleton. See #6863 for details.

    Note for triage: capturing the scoped service provider is a good idea. I wasn't sure how to do it before, but I think I have an idea now.

  2. prochnowc commented on Jun 12, 2017

    @prochnowc
    Author

    Thanks for the reply. I've already worked it around registering DbContextOptions on my own as scoped service.

  3. added this to the 2.0.0 milestone on Jun 12, 2017
  4. self-assigned this
    on Jun 12, 2017
  5. removed their assignment
    on Sep 1, 2024
  6. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions