Skip to content

AddDbContext: DbContextOptions should have the same ServiceLifetime as TContext #6863

@jussik

Description

@jussik

Steps to reproduce

Make an ASP.NET Core application with a scoped service that provides a connection string to Entity Framework Core per-request.

services.AddDbContext<MyDbContext>((srv, opts) =>
{
    string cs = srv.GetRequiredService<SomeScopedService>().ConnectionString;
    if (string.IsNullOrEmpty(cs))
        throw new NotSupportedException("No ConnectionString");
    opts.UseSqlServer(cs);
});

The issue

This does not work as expected using the default AddDbContext, it does not return the correct instance of the requested scoped service. If I make my own identical AddDbContext except for registering DbContextOptions and DbContextOptions<TContext> as scoped then it works as expected; the correct instance of the scoped service is accessed and I get my connection string.

Proposal

I propose using the contextLifetime parameter of AddDbContext<TContext> to register DbContextOptions and DbContextOptions<TContext> using the same ServiceLifetime as TContext.

Further technical details

EF Core version: 1.0.1
ASP.NET Core version: 1.0.1
Operating system: Windows 7
Visual Studio version: VS 2015 Update 3

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions