.NET 6中System.AggregateException服务构造失败问题求助
问题解决:依赖注入无法解析IDataBaseContext服务
问题原因
你向DI容器注册了DataBaseContext具体类,但GetUsersService依赖的是IDataBaseContext接口,容器不知道该用哪个实现来匹配这个接口,导致服务构造失败。
解决方案
1. 注册接口与实现的映射
有两种方式将IDataBaseContext和DataBaseContext关联到DI容器中:
- 方式一:单独注册接口映射
在注册DataBaseContext之后添加一行代码:
builder.Services.AddDbContext<DataBaseContext>(options => options.UseSqlServer(connectionString)); // 新增:将IDataBaseContext映射到DataBaseContext实例 builder.Services.AddScoped<IDataBaseContext>(provider => provider.GetRequiredService<DataBaseContext>());
- 方式二:注册DbContext时直接指定接口
如果DataBaseContext已经实现了IDataBaseContext,可以直接在AddDbContext时同时注册接口:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); // 直接注册接口和对应的实现类 builder.Services.AddDbContext<IDataBaseContext, DataBaseContext>(options => options.UseSqlServer(connectionString));
2. 确认DataBaseContext实现了IDataBaseContext
确保你的DataBaseContext类正确继承并实现了IDataBaseContext接口,比如:
public class DataBaseContext : DbContext, IDataBaseContext { // 实现IDataBaseContext中定义的所有成员,比如相关DbSet public DbSet<User> Users { get; set; } // ... 其他上下文代码 }
修改后的完整Program.cs示例
using Microsoft.EntityFrameworkCore; using Store.Application.Interfaces.Contexts; using Store.Application.Services.Users.Queries.GetUsers; using Store.Persistence.Contexts; var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorPages(); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); // 使用方式二注册接口与实现 builder.Services.AddDbContext<IDataBaseContext, DataBaseContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddTransient<IGetUsersService, GetUsersService>(); var app = builder.Build(); // 后续的中间件配置 app.UseRouting(); app.MapRazorPages(); app.Run();
内容的提问来源于stack exchange,提问作者S.M_Emamian
相关产品推荐
相关产品推荐

