ASP.NET Core Web API - 尝试激活 'Services.CurrentUserService' 时无法解析类型 'IHttpContextAccessor' 的服务

ASP.NET Core Web API - Unable to resolve service for type 'IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'

我正在 ASP.NET Core-6 Web API 用户身份验证登录中实施 CurrentUser 服务。我正在使用 IdentityDbContext:

ICurrentUserService:

public interface ICurrentUserService
{
    public string UserId { get; }
    public string UserName { get; }
    bool IsAuthenticated { get; }
    public string IpAddress { get; }
}

当前用户服务:

using Microsoft.AspNetCore.Http;
using System.Security.Claims;

public class CurrentUserService : ICurrentUserService
{
    public string UserId { get; }
    public string UserName { get; }
    public bool IsAuthenticated { get; }
    public string IpAddress { get; }

    public CurrentUserService(IHttpContextAccessor httpContextAccessor)
    {
        IpAddress = httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress.ToString();
        UserName = httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
        UserId = httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
        IsAuthenticated = UserId != null;
    }
}

然后在 Program.cs 我有这个:

var builder = WebApplication.CreateBuilder(args);

// Register CurrentUserService
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

var app = builder.Build();

但是当我尝试 运行 应用程序时,我收到此错误:

System.AggregateException
  HResult=0x80131500
  Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Services.ICurrentUserService Lifetime: Scoped ImplementationType: Services.CurrentUserService': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'.)
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Program.<Main>$(String[] args) in C:\MyApp\WebApi\Program.cs:line 15

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: Services.ICurrentUserService Lifetime: Scoped ImplementationType: Services.CurrentUserService': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'.
var app = builder.Build()

是第 15 行

如何解决这个问题?

谢谢。

注册HttpContextAccessor依赖项。

builder.Services.AddHttpContextAccessor();
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpContextAccessor();

// Register CurrentUserService
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

var app = builder.Build();

参考资料

Use HttpContext from custom components