.NET 8 API使用AddScoped注册服务触发AggregateException如何解决?
问题原因与解决方法
核心问题
你的TodoItemsService构造函数直接依赖DbSet<TodoItem>,但.NET依赖注入容器不会自动注册DbSet类型——DbSet是DbContext的属性,必须通过DbContext实例来获取,无法被DI容器直接解析。
修复步骤
1. 修改TodoItemsService的构造函数
将依赖从DbSet<TodoItem>替换为你的DbContext(比如TodoApiDbContext),通过DbContext获取DbSet:
public class TodoItemsService : ITodoItemsService { private readonly DbSet<TodoItem> _todoItems; // 注入DbContext而非直接注入DbSet public TodoItemsService(TodoApiDbContext dbContext) { _todoItems = dbContext.TodoItems; } public IQueryable<TodoItem> GetAbunch(string[] myAnimals) { // 正常使用_todoItems进行数据操作 return _todoItems.Where(item => ...); } }
2. 确保DbContext已注册到DI容器
在Program.cs中,必须先注册DbContext,再注册你的业务服务:
// 注册DbContext(根据你的数据库类型调整,示例为SQL Server) builder.Services.AddDbContext<TodoApiDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); // 注册业务服务 builder.Services.AddScoped<ITodoItemsService, TodoItemsService>();
补充说明
DbContext是DI容器可管理的服务(通过AddDbContext完成注册),而DbSet只是DbContext的成员,不会被单独纳入DI管理。直接注入DbContext不仅能解决当前的解析异常,还能让你更灵活地控制数据库操作的生命周期(比如事务管理),符合EF Core的标准使用规范。
内容的提问来源于stack exchange,提问作者sam sergiy klok
相关产品推荐
相关产品推荐

