Question about Dependency Injection
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.
- ID: a111b14d-2c56-f0a9-d318-f99ae6bb016e
- Version Independent ID: 91430704-1e14-9b10-9fd1-d5a19cc5d380
- Content: Work with SQLite in an ASP.NET Core Razor Pages app
- Content Source: aspnetcore/tutorials/razor-pages-vsc/sql.md
- Product: aspnet-core
- GitHub Login: @Rick-Anderson
- Microsoft Alias: riande
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; }
}
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 thanks for pointing that out. I'll add that link to this doc.