C# 如何在ASP.NET Core 2.0中获取我想要的DbContext实例?

C# 如何在ASP.NET Core 2.0中获取我想要的DbContext实例?,c#,entity-framework,asp.net-core,dependency-injection,C#,Entity Framework,Asp.net Core,Dependency Injection,如何在ASP.NET Core 2.0中获取我想要的DbContext实例? 为了连接数据库,我使用了服务 string connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<MobileContext>(options => options.UseSqlServer(connection)); string connection=Configura

如何在ASP.NET Core 2.0中获取我想要的DbContext实例? 为了连接数据库,我使用了服务

string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MobileContext>(options => options.UseSqlServer(connection));
string connection=Configuration.GetConnectionString(“DefaultConnection”);
services.AddDbContext(options=>options.UseSqlServer(connection));
这在以下章节中进行了描述:

摘录:

EF Core支持将DbContext与依赖项注入容器一起使用。可以使用AddDbContext方法将DbContext类型添加到服务容器中

AddDbContext将使您的DbContext类型、TContext和相应的DbContextOptions都可以从服务容器中注入

应用程序代码(在ASP.NET核心中):

应用程序代码(直接使用ServiceProvider,不太常见):

使用(var context=serviceProvider.GetService())
{
//做事
}
var options=serviceProvider.GetService();
公共类BloggingContext:DbContext
{
公共博客上下文(DbContextOptions)
:基本(选项)
{ }
公共数据库集博客{get;set;}
}
您的应用程序现在可以在实例化上下文时传递DbContextOptions,如下所示:

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}
var optionsBuilder=new DbContextOptionsBuilder();
optionsBuilder.UseSqlite(“数据源=blog.db”);
使用(var context=newbloggingcontext(optionsBuilder.Options))
{
//做事
}

您应该在服务定位器示例代码中创建一个作用域,因为上下文将被限定作用域,并且不能直接从注入的服务提供商检索。
using (var context = serviceProvider.GetService<BloggingContext>())
{
  // do stuff
}

var options = serviceProvider.GetService<DbContextOptions<BloggingContext>>();
public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}