Skip to content

AddDbContextFactory registers a DbContext, but without it coming from the factory #35485

Closed

Description

@roji

AddDbContextFactory also registers a Scoped DbContext (#25164); but that context is instantiated directly, without it coming from the factory.

Repro
var services = new ServiceCollection();
services.AddDbContextFactory<BlogContext, BlogContextFactory>(o =>
    o.UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false"));
await using var serviceProvider = services.BuildServiceProvider();
var factory = (BlogContextFactory)serviceProvider.GetRequiredService<IDbContextFactory<BlogContext>>();

var scope = serviceProvider.CreateScope();
await using var context = scope.ServiceProvider.GetService<BlogContext>();

Console.WriteLine(factory.WasCalled); // Prints false

public class BlogContext(DbContextOptions<BlogContext> options) : DbContext(options)
{
    public DbSet<Blog> Blogs { get; set; }
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class BlogContextFactory(DbContextOptions<BlogContext> options) : IDbContextFactory<BlogContext>
{
    public bool WasCalled { get; set; }

    public BlogContext CreateDbContext()
    {
        WasCalled = true;
        return new BlogContext(options);
    }
}

Activity

  1. self-assigned this
    on Jan 16, 2025
  2. added a commit that references this issue on Jan 16, 2025
    76e8260
  3. added this to the 10.0.0 milestone on Jan 16, 2025
  4. added 2 commits that reference this issue on Jan 16, 2025
    296128f
    3f22ec8
  5. added a commit that references this issue on Jan 17, 2025
    47e5d25
  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

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions