.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映射到ReadRepoIUnitOfWork映射到UnitOfWork
4. 清理并重新编译项目
执行以下操作确保所有修改生效:
- 清理项目:右键项目 → 清理
- 重建项目:右键项目 → 生成
- 重新运行应用
内容的提问来源于stack exchange,提问作者Alexander Kushner
相关产品推荐
相关产品推荐

