You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2017 Razor Pages项目MyDbContext依赖注入失败问题求助

嘿,这个问题我之前也碰到过!错误提示Unable to resolve service for type 'OESAC.Data.MyDbContext'本质是ASP.NET Core的依赖注入容器里没有注册你的MyDbContext类,所以当Courses页面的IndexModel尝试通过构造函数获取这个DbContext实例时,系统不知道怎么创建它。

下面一步步帮你解决:

步骤1:修改Startup.cs注册DbContext

在你的VS2017 Razor Pages项目里找到Startup.cs文件(ASP.NET Core 2.x项目默认会有这个文件),打开它的ConfigureServices方法,添加注册MyDbContext的代码:

原来的ConfigureServices可能只有services.AddMvc();,现在加上DbContext注册逻辑:

services.AddDbContext<MyDbContext>(options =>
    options.UseSqlite(@"Data source=oesac_new.db"));

完整的Startup.cs示例如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OESAC.Data;

namespace OESAC
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            
            // 核心:把MyDbContext注册到依赖注入容器
            services.AddDbContext<MyDbContext>(options =>
                options.UseSqlite(@"Data source=oesac_new.db"));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseMvc();
        }
    }
}

步骤2:(可选)调整数据库文件路径

你的连接字符串Data source=oesac_new.db会在应用的运行目录(比如bin/Debug/netcoreapp2.1)查找数据库文件。如果想让数据库文件放在项目根目录,可以修改路径为:

options.UseSqlite(@"Data source=../oesac_new.db");

步骤3:(可选)初始化数据库

如果oesac_new.db还不存在,打开Visual Studio的包管理器控制台(工具 → NuGet包管理器 → 包管理器控制台),执行以下命令生成迁移并创建数据库表:

Add-Migration InitialCreate
Update-Database

补充:为什么首页能正常运行?

因为首页的PageModel没有依赖注入MyDbContext,系统不需要去创建这个服务实例;而Courses页面的IndexModel构造函数明确需要MyDbContext,这时候容器里没注册对应的服务,就抛出了这个错误。

内容的提问来源于stack exchange,提问作者JustJohn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:38:05