简体   繁体   中英

How does DbContextOptions get injected?

I saw a lot of code like this below:

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

    public DbSet<Book> Books { get; set; }
    ...
}

So I think DbContextOptions<EFCoreContext> options is injected by DI via:

// Startup.cs
public void ConfigureServices(IServiceCollection services) 
{
    services.AddDbContext<EFCoreContext>(   // register EFCoreContext so it can be injected
        options => options.UseSqlServer(connection)   // tell EF that you're using an SQL Server database by using the UseSqlServer method
    ); 
}

But I checked the source code ( https://github.com/dotnet/efcore/blob/main/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs ) of AddDbContext, I couldn't find any code related to the injection of DbContextOptions<EFCoreContext> .

I have two questions:

  1. How does it get injected?

  2. Why do we need to have public EFCoreContext(DbContextOptions<EFCoreContext> options) : base(options) { } ? It looks like this piece of code just tells EF that we will be using EFCoreContext , as DbContext, but we have already register EFCoreContext in startup.cs, any class's constructor takes a EFCoreContext will work, isn't it?

  1. You can inject your dbcontext on any class or any contoller like the below:

    Public class YourService{

    private readonly EFCoreContext _dbContext; constructor(EFCoreContext dbContext) _dbContext= dbContext; }

  2. The base option is used to override the default behavior of ef core dbcontext class. But you can do the same on the startup class also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM