EF Core 在 ASP.NET Core 中通过 DI 注册 DbContext 并构造注入使用,推荐在 Program.cs 用 AddDbContext 注册(Scoped 生命周期),控制器中注入后直接调用异步方法操作数据。
EF Core 在 ASP.NET Core 中通过依赖注入(DI)注册和使用 DbContext,这是官方推荐且最简洁的方式。核心思路是:在 Program.cs(或 Startup.cs)中将 DbContext 类型注册进 DI 容器,然后在控制器、服务等需要的地方通过构造函数注入即可。
ASP.NET Core 6+ 推荐在 Program.cs 中配置服务:
var builder = WebApplication.CreateBuilder(args);
// 从配置中读取连接字符串
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
// 注册 DbContext,使用 SQL Server
builder.Services.AddDbContext(options =>
options.UseSqlServer(connectionString));
var app = builder.Build();
注册后,直接在控制器构造函数中声明 DbContext 类型参数,框架会自动解析并传入实例:
public class ProductsController : ControllerBase { private readonly AppDbContext _context; public ProductsController(AppDbContext context) { _context = context; } [HttpGet] public async Task
> Get() { return await _context.Products.ToListAsync(); } }
如果 DbContext 需要额外依赖(如 ILogger 或 IOptions),可直接在构造函数中声明,DI 容器会一并解析:
根据场景可调整注册行为:
AddDbContext(ServiceLifetime.Singleton) (不推荐,易出错)基本上就这些。只要注册正确、注入自然、不手动管理生命周期,EF Core 和 ASP.NET Core 的配合非常顺滑。