.NET Core Web API集成MongoDB启动服务构造失败求助
解决.NET Core Web API中DatabaseContext服务无法解析的问题
报错信息:
'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: TeapiocaMIC.Service.LoginService Lifetime: Scoped ImplementationType: TeapiocaMIC.Service.LoginService': Unable to resolve service for type 'DatabaseContext' while attempting to activate 'TeapiocaMIC.Service.LoginService'.)'
问题根源
你的DatabaseContext采用私有构造函数+静态单例的实现,但DI容器注册时直接使用AddScoped<DatabaseContext>(),导致两个核心问题:
- DI容器无法访问私有构造函数,无法创建实例
- DI容器不知道
DatabaseContext需要IDatabaseSettings和IMongoClient这两个依赖项
另外,代码中同时存在Startup.cs和Program.cs的服务注册,容易造成配置冲突,建议统一使用.NET Core 6+推荐的Program.cs顶级语句模式配置。
修复步骤
1. 修改DatabaseContext实现,适配DI容器
移除静态单例逻辑,将私有构造函数改为公共构造函数,让DI容器可以正常注入依赖:
public class DatabaseContext { private readonly IMongoDatabase _database; // 改为公共构造函数,允许DI容器注入依赖 public DatabaseContext(IDatabaseSettings settings, IMongoClient mongoClient) { _database = mongoClient.GetDatabase(settings.DatabaseName); } public IMongoCollection<MenuModules> MenuModulesCollection => _database.GetCollection<MenuModules>(TableNames.MenuModules); public IMongoCollection<Login> LoginCollection => _database.GetCollection<Login>(TableNames.Login); public IMongoCollection<Users> UserCollection => _database.GetCollection<Users>(TableNames.Users); public IMongoCollection<Roles> RolesCollection => _database.GetCollection<Roles>(TableNames.Roles); public IMongoCollection<Store> StoresCollection => _database.GetCollection<Store>(TableNames.Store); public IMongoCollection<StoresUsers> StoreUsersCollection => _database.GetCollection<StoresUsers>(TableNames.StoreUsers); }
2. 在Program.cs中正确注册DatabaseContext
替换原有的builder.Services.AddScoped<DatabaseContext>(),明确告诉DI容器如何创建DatabaseContext实例:
// 替换原DatabaseContext注册代码 builder.Services.AddScoped<DatabaseContext>(sp => { var settings = sp.GetRequiredService<IDatabaseSettings>(); var mongoClient = sp.GetRequiredService<IMongoClient>(); return new DatabaseContext(settings, mongoClient); });
3. 清理冗余配置并修正依赖注册
- 删除
Startup.cs中的服务注册逻辑(.NET Core 6+无需单独的Startup类) - 修正
IMongoClient的注册,改用配置文件中的连接字符串,避免硬编码:
// 保留并修正已有的配置注册 builder.Services.Configure<DatabaseSettings>( builder.Configuration.GetSection(nameof(DatabaseSettings))); builder.Services.AddSingleton<IDatabaseSettings>(sp => sp.GetRequiredService<IOptions<DatabaseSettings>>().Value); builder.Services.AddSingleton<IMongoClient>(sp => new MongoClient(sp.GetRequiredService<IDatabaseSettings>().ConnectionString));
4. 验证LoginService依赖注入
LoginService的构造函数已正确依赖DatabaseContext,只要DatabaseContext注册正常,DI容器会自动解析并注入:
public class LoginService { private readonly IMongoCollection<Login> _login; public LoginService(DatabaseContext databaseContext) { _login = databaseContext.LoginCollection; } public Login GetByUserNameAndPassword(string userName, string password) { return _login.Find(login => login.UserName == userName && login.Password == password).FirstOrDefault(); } }
内容的提问来源于stack exchange,提问作者Siva
相关产品推荐
相关产品推荐

