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

ASP.NET Core依赖注入报错:无法解析IVideoServices服务

问题:ASP.NET Core 解析 IVideoServices 服务失败

我跟着教程搭建简易视频存储API,调用Get Videos接口时触发System.InvalidOperationException,提示激活VideosController时无法解析IVideoServices服务。新版ASP.NET Core没有Startup.cs,我已经把教程里的builder.Services.AddTransient<IVideoServices, VideoServices>()配置加到Program.cs里了,但问题依然存在,相关代码如下,求排查。

错误详情

System.InvalidOperationException: Unable to resolve service for type 'Wypozyczalnia.WebApi.Controllers.IVideoServices' while attempting to activate 'Wypozyczalnia.WebApi.Controllers.VideosController'.

   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

   at lambda_method3(Closure , IServiceProvider , Object[] )

   at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)

   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)

   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)

   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()

--- End of stack trace from previous location ---

   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)

   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)

   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)

   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)

   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)

   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)

   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)

   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

相关代码文件

VideosController.cs

using Microsoft.AspNetCore.Mvc;

namespace Wypozyczalnia.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class VideosController : ControllerBase
    {
        private readonly IVideoServices _videoServices;
        public VideosController(IVideoServices videoServices)
        {
             _videoServices = videoServices;
        }

        [HttpGet]
        public IActionResult GetVideos()
        {
            return Ok(_videoServices.GetVideos());
        }
    }
}

VideoServices.cs

namespace Wypozyczalnia.Core
{
    public class VideoServices : IVideoServices
    {
        public List<Video> GetVideos()
        {
            return new List<Video>
            {
                new Video
                {
                    Title = "Test",
                    Genre = "Fantasy"
                }
            };
        }
    }
}

IVideoServices.cs

namespace Wypozyczalnia.Core
{
    public interface IVideoServices
    {
        List<Video> GetVideos();
    }
}

Video.cs

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace Wypozyczalnia.Core
{
    public class Video
    {
        [BsonId]
        [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
        public string Id { get; set; }
        public string Title { get; set; }
        public string Genre { get; set; }
        public string Director  { get; set; }    
        public double Time { get; set; }
        public double Rating { get; set; }
        public string Description { get; set; }
        public string Cast { get; set; }
        public string Added { get; set; }
    }
}

Program.cs

using Wypozyczalnia.Core;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddTransient<IVideoServices, VideoServices>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
解决方案

问题出在命名空间引用不一致:

  • IVideoServices实际定义在Wypozyczalnia.Core命名空间下,但VideosController里没有引用这个命名空间,导致编译器认为IVideoServices是Wypozyczalnia.WebApi.Controllers命名空间下的类型,DI容器自然找不到对应的服务实现。

修复步骤:

  1. 在VideosController.cs顶部添加Wypozyczalnia.Core的命名空间引用:
using Microsoft.AspNetCore.Mvc;
using Wypozyczalnia.Core; // 新增这行引用

namespace Wypozyczalnia.WebApi.Controllers
{
    // 原有控制器代码保持不变
}
  1. 重新编译运行项目,此时DI容器能正确识别IVideoServices的实际类型,即可正常注入VideoServices实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:15:54