ASP.NET Core 依赖关系注入中的 DbContext
在许多 Web 应用程序中,每个 HTTP 请求都对应于单个工作单元。 这使得上下文生存期与请求的生存期相关,成为 Web 应用程序的一个良好默认值。
使用依赖关系注入配置 ASP.NET Core 应用程序。 可以使用 Startup.cs 的 ConfigureServices 方法中的 AddDbContext 将 EF Core 添加到此配置。 例如:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<TestContext>(
options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
}
此示例将名为 ApplicationDbContext 的 DbContext 子类注册为 ASP.NET Core 应用程序服务提供程序(也称为依赖关系注入容器)中的作用域服务。 上下文配置为使用 SQL Server 数据库提供程序,并将从 ASP.NET Core 配置读取连接字符串。 在 中的何处调用 AddDbContext 通常不重要。
ApplicationDbContext 类必须公开具有 DbContextOptions<ApplicationDbContext> 参数的公共构造函数。 这是将 AddDbContext 的上下文配置传递到 DbContext 的方式。 例如:
using Addict.Entity.Models.TestModel;
using Microsoft.EntityFrameworkCore;
namespace Addict.Entity
{
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options)
: base(options)
{
}
public DbSet<Table1> Table1 { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Table1>().ToTable("Table1");
}
}
}
然后,ApplicationDbContext 可以通过构造函数注入在 ASP.NET Core 控制器或其他服务中使用。 例如:
public class HomeController : Controller
{
private readonly TestContext _context;
public HomeController(TestContext context)
{
_context = context;
}
[HttpGet]
public List<Table1> Test()
{
return _context.Table1.Where(a => a.ShopkeeperId == 1).Take(10).ToList();
}
}