简体   繁体   English

DbContextOptions 是如何被注入的?

[英]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:所以我认为DbContextOptions<EFCoreContext> options是通过 DI 注入的:

// 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> .但是我查看了 AddDbContext 的源代码( https://github.com/dotnet/efcore/blob/main/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs ),我找不到任何与注入DbContextOptions<EFCoreContext>相关的代码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) { } ?为什么我们需要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?看起来这段代码只是告诉 EF 我们将使用EFCoreContext作为 DbContext,但是我们已经在 startup.cs 中注册了EFCoreContext ,任何类的构造函数采用EFCoreContext都可以工作,不是吗?

  1. You can inject your dbcontext on any class or any contoller like the below:您可以在任何类或任何控制器上注入 dbcontext,如下所示:

    Public class YourService{公共类 YourService{

    private readonly EFCoreContext _dbContext;私有只读 EFCoreContext _dbContext; constructor(EFCoreContext dbContext) _dbContext= dbContext;构造函数(EFCoreContext dbContext)_dbContext=dbContext; } }

  2. The base option is used to override the default behavior of ef core dbcontext class. base 选项用于覆盖 ef 核心 dbcontext 类的默认行为。 But you can do the same on the startup class also.但是你也可以在启动类上做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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