AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

Question about Dependency Injection

Open nelfer opened this issue 8 years ago • 3 comments

Hi, I'm learning about dependency injection and I understood the WebContext injection. But in this line:

using (var context = new MovieContext(serviceProvider.GetRequiredService<DbContextOptions<MovieContext>>()))

It seems like the we're requesting a DbContextOptions service, but that was never registered. Or by registering the DbContext it automatically adds this service? Because it is a parameter for the constructor perhaps? I'm guessing here.

Thanks!


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

nelfer avatar Aug 25 '18 02:08 nelfer

See GetRequiredService<T>(IServiceProvider)

It's requesting a service of type T from the IServiceProvider and

public class RazorPagesMovieContext : DbContext
{
    public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)
        : base(options)
    {
    }

    public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }
}

Rick-Anderson avatar Aug 25 '18 16:08 Rick-Anderson

Ah found it in the documentation of AddDbContext: https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext#using-dbcontext-with-dependency-injection

Basically when registering DbContext it automatically registers DbContextOptions as well, because it's a required constructor argument. Thanks

nelfer avatar Aug 25 '18 18:08 nelfer

@nelfer thanks for pointing that out. I'll add that link to this doc.

Rick-Anderson avatar Aug 25 '18 18:08 Rick-Anderson