ASP.NET Core Web API无法解析DbContext依赖问题求助
问题描述
我有一个ASP.NET Core Web应用,已完成DbContext的注册:
string connectionString = builder.Configuration .GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<HomeNotificationsDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddHomeNotificationApplicationServices(typeof(IUserService));
AddHomeNotificationApplicationServices是一个扩展方法,通过反射将所有相关服务注册为scoped生命周期。Web应用启动正常,但在Web API中用同样的方式注册相同服务时,出现以下错误:
Unable to resolve service for type 'HomeNotifications.Data.HomeNotificationsDbContext' while attempting to activate 'HomeNotifications.Services.Data.HomeAuthenticationService'.
HomeAuthenticationService通过依赖注入获取DbContext的只读实例:
public class HomeAuthenticationService : IHomeAuthenticationService { private readonly HomeNotificationsDbContext dbContext; public HomeAuthenticationService(HomeNotificationsDbContext dbContext) { this.dbContext = dbContext; } // ... }
DbContext、Web应用和Web API分属不同类库,服务通过DI初始化。我尝试在API中将DbContext注册为scoped服务,但因无法访问Web应用配置而失败,考虑过把连接字符串添加到API配置文件,但不确定是否正确,作为新手寻求建议。
解决方案
仅在Web应用的Program.cs中注册所有服务(包括DbContext和业务服务),不在Web API的Program.cs中重复注册服务。
原因分析
- 当Web API单独注册服务时,它的DI容器中没有注册
HomeNotificationsDbContext,而业务服务(如HomeAuthenticationService)依赖该DbContext,导致激活服务时无法解析依赖。 - 若Web API和Web应用属于同一解决方案且存在关联(而非完全独立的服务),无需重复搭建DI配置,复用Web应用的注册逻辑即可避免依赖缺失问题。如果是完全独立的API项目,才需要在API的配置文件中添加连接字符串并单独注册DbContext,但根据场景显然不属于这种情况。
内容的提问来源于stack exchange,提问作者Krasimir Dimitrov
相关产品推荐
相关产品推荐

