ASP.NET 控制器中的 Core 6 依赖注入 return System.InvalidOperationException: 无法解析服务

ASP.NET Core 6 Dependency injection in controller return System.InvalidOperationException: Unable to resolve service

我正在尝试使用 ASP.NET Core 6 开发一个 Web API 项目,但是我得到这个错误,依赖注入似乎有错误,但我没有找到这个:

System.InvalidOperationException: Unable to resolve service for type 'api.Interface.IUsersService' while attempting to activate 'api.Controllers.UsersController'.

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.b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.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.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.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)

Startup.cs :

public void ConfigureServices(IServiceCollection services)
{
       string connectionString = Configuration.GetConnectionString("DefaultConnection");
       services.AddDbContext<DataContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
       services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
        {
            build.WithOrigins("http://localhost:8080")
                 .AllowAnyMethod()
                 .AllowAnyHeader();
        }));
        services.AddMvc();
        services.AddControllers();
        services.AddScoped<IJwtUtils, JwtUtils>();
        services.AddScoped<IUsersService, UsersService>();
        services.AddScoped<IQrcodesService, QrcodesService>();
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        services.AddControllers().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        });
}

IUsersService.cs:

using api.Response;
using System.Collections.Generic;

namespace api.Interface
{
    public interface IUsersService
    {
        // ...
    }
}

UsersService.cs:

using api.Authorization;
using api.Helpers;
using api.Interface;
using api.Response;
using AutoMapper;
using System.Collections.Generic;
using System.Linq;
using BCryptNet = BCrypt.Net.BCrypt;

namespace api.Services
{
    public class UsersService : IUsersService
    {
        private DataContext _context;
        private IJwtUtils _jwtUtils;
        private readonly IMapper _mapper;

        public UsersService(
            DataContext context,
            IJwtUtils jwtUtils,
            IMapper mapper)
        {
            _context = context;
            _jwtUtils = jwtUtils;
            _mapper = mapper;
        }

        // ...
    }
}

UsersController.cs:

using api.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using api.Response;
using api.Authorization;
using api.Interface;

namespace api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IUsersService _userService;
        private readonly AppSettings _appSettings;

        public UsersController(
            IUsersService userService,
            IOptions<AppSettings> appSettings)
        {
            _userService = userService;
            _appSettings = appSettings.Value;
        }

        // ...
    }
}

DataContext.cs:

using System;
using Microsoft.EntityFrameworkCore;
using api.Response;
using BCryptNet = BCrypt.Net.BCrypt;
using api.Authorization;

namespace api.Helpers
{
    public class DataContext : DbContext
    {
        public DataContext() { }

        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<QRcode> QRcodes { get; set; }
        public DbSet<Activity> Activities { get; set; }
        public DbSet<Giustification> Giustifications  { get; set; }
       
        // ...
    }
}

JwtUtils.js:

public class JwtUtils : IJwtUtils
{
    private readonly AppSettings _appSettings;

    public JwtUtils(IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
    }
           //...
}

我正在使用带有 mysql '8.0.27' 和 .NET 6 的 pomelo 6.0.1。

我觉得这个 services.Configure(Configuration.GetSection("AppSettings")); 行需要先执行 services.AddScoped();

我找到了解决方案,项目从 .net 5 开始,然后迁移到 6。 新版本已更改文件Program.cs

我的新Program.cs

using api;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

var startup = new Startup(builder.Configuration);


startup.ConfigureServices(builder.Services);

var app = builder.Build();

startup.Configure(app, app.Environment);

app.Run();

有关如何迁移项目的更多信息:Migrate from ASP.NET Core 5.0 to 6.0 我要感谢大家的回答。