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

.NET Core 7.0激活HomeController时无法解析IDatabase服务求助

.NET Core 7.0依赖注入异常排查:无法解析IDatabase服务

异常详情

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type
'MoviesCore.Controllers.IDatabase' while attempting to activate
'MoviesCore.Controllers.HomeController'.

相关代码片段

HomeController与IDatabase接口

namespace MoviesCore.Controllers
{
    public class HomeController: Controller
    {
        const int SUCCESS = 1;
        private readonly ILogger _logger;
        private readonly IDatabase _database;

        public HomeController (ILogger<HomeController> logger, IDatabase database)
        {
            _logger = logger;
            _database = database;
        }
    }
}

namespace MoviesCore.Interfaces
{
    public interface IDatabase
    {
        Task<int> CheckCatInMovie (int MovieID,int CategoryID);
        Task<IList<CategoryLU>> GetCategories ();
    }
}

IDatabase实现类Database

namespace MoviesCore.Services
{
    public class Database : IDatabase
    {
        private readonly MovieDBContext _context;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IReadRepo _readRepo;

        public Database (MovieDBContext context, IUnitOfWork unitOfWork, IReadRepo readRepo)
        {
            _context = context;
            _unitOfWork = unitOfWork;
            _readRepo = readRepo;
        }

        public async Task<int> CheckCatInMovie(int MovieID, int CategoryID)
        {
            IList<MovieCategory> categories = await _unitOfWork.ReadRepo.GetListWithPredicate<MovieCategory>(mc => mc.MovieID == MovieID && mc.CategoryLUID == CategoryID);
            return categories.Count;
        }

        public async Task<IList<CategoryLU>> GetCategories ()
        {
            IList<CategoryLU> categories = await _unitOfWork.ReadRepo.GetList<CategoryLU> ();
            return categories;
        }
     }
}

MovieDBContext定义

namespace Api.Models
{
    public class MovieDBContext: DbContext
    {
        public MovieDBContext(DbContextOptions<MovieDBContext> options) : base(options) { }
        public MovieDBContext () { }

        public DbSet<Movie>? Movie { get; set; }
        public DbSet<MovieCategory>? MovieCategory { get; set; }
        public DbSet<MovieNamesPosition>? MovieNamesPosition { get; set; }
        public DbSet<PositionsLU>? PositionLU { get; set; }
        public DbSet<NamesLU>? NamesLU { get; set; }
        public DbSet<CategoryLU>? CategoryLU { get; set; }
        public DbSet<Movie>? spSearchMovies { get; set; }
        public DbSet<spGetCats>? spGetCats { get; set; }
    }
}

Program.cs服务注册代码

var builder = WebApplication.CreateBuilder (args);

// Add services to the container.
builder.Logging.ClearProviders ();
builder.Logging.AddConsole ();
builder.Services.AddControllersWithViews ();
builder.Services.AddMvc ();
builder.Services.AddDbContext<MovieDBContext> (opt =>opt.UseSqlServer ("Server = (localdb)\\MSSQLLocalDB;Initial Catalog = MoviesCore;Integrated Security = True;"));
builder.Services.AddTransient<IReadRepo, ReadRepo>();
builder.Services.AddTransient<IUnitOfWork, UnitOfWork> ();
builder.Services.AddTransient<IDatabase,MoviesCore.Services.Database> ();
builder.Services.AddTransient<IHttpContextAccessor,HttpContextAccessor> ();
builder.Services.AddRazorPages ();

var app = builder.Build ();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment ())
{
    app.UseExceptionHandler ("/Shared/Error");
    app.UseHsts ();
}

app.UseHttpsRedirection ();
app.UseStaticFiles ();

app.UseRouting ();

app.UseAuthorization ();
app.MapRazorPages ();

app.MapControllerRoute (
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run ();

排查与修复步骤

1. 确认命名空间引用正确性

  • HomeController文件:在顶部添加using MoviesCore.Interfaces;,确保代码中IDatabase指向正确的接口类型,避免因命名空间缺失导致的类型识别错误。
  • Program.cs文件:注册IDatabase服务时,确保引用了MoviesCore.Interfaces命名空间。可直接添加using MoviesCore.Interfaces;或使用完整命名空间注册:
    builder.Services.AddTransient<MoviesCore.Interfaces.IDatabase, MoviesCore.Services.Database>();
    

2. 移除MovieDBContext的无参数构造函数

当前MovieDBContext存在无参数构造函数,虽依赖注入容器会优先使用带参数构造函数,但无参数构造函数可能引发潜在配置问题。建议移除该构造函数,确保容器始终用正确配置初始化上下文:

namespace Api.Models
{
    public class MovieDBContext: DbContext
    {
        public MovieDBContext(DbContextOptions<MovieDBContext> options) : base(options) { }

        // 删除无参数构造函数
        // public MovieDBContext () { }

        //... DbSet定义
    }
}

3. 验证依赖链完整性

确认Database类的所有依赖(MovieDBContext、IUnitOfWork、IReadRepo)均已在Program.cs中正确注册:

  • MovieDBContext通过AddDbContext注册完成
  • IReadRepo映射到ReadRepo
  • IUnitOfWork映射到UnitOfWork

4. 清理并重新编译项目

执行以下操作确保所有修改生效:

  • 清理项目:右键项目 → 清理
  • 重建项目:右键项目 → 生成
  • 重新运行应用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:25:41