System.AggregateException:“Some services are not able to be constructed, Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor
System.AggregateException:“Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CSFramework.LicenseCoreWebApi.UserContext Lifetime: Scoped ImplementationType: CSFramework.LicenseCoreWebApi.UserContext': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'CSFramework.LicenseCoreWebApi.UserContext'.) (Error while validating the service descriptor 'ServiceType: CSFramework.LicenseCore.Interfaces.IUserContext Lifetime: Scoped ImplementationType: CSFramework.LicenseCoreWebApi.UserContext': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'CSFramework.LicenseCoreWebApi.UserContext'.) (Error while validating the service descriptor 'ServiceType: CSFramework.LicenseServerV3.Business.LicenseAdminToolBusiness Lifetime: Scoped ImplementationType: CSFramework.LicenseServerV3.Business.LicenseAdminToolBusiness': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'CSFramework.LicenseCoreWebApi.UserContext'.) (Error while validating the service descriptor 'ServiceType: CSFramework.LicenseCore.Interfaces.IDataServiceAdmin Lifetime: Scoped ImplementationType: CSFramework.LicenseServerV3.Business.LicenseAdminToolBusiness': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'CSFramework.LicenseCoreWebApi.UserContext'.)”
错误原因
无法解析Microsoft.AspNetCore.Http.IHttpContextAccessor接口服务类型。
Microsoft.AspNetCore.Http.IHttpContextAccessor接口不能作为自动注入接口的参数使用,如:
public UserContext(IServiceProvider serviceProvider, IHttpContextAccessor httpContext)
{
_serviceProvider = serviceProvider;
this.IP = httpContext.HttpContext.GetClientIP();
}
解决方案
注入 HttpContextAccessor :
builder.Services.AddHttpContextAccessor();
注入后,建议改用下面代码:
取消 Microsoft.AspNetCore.Http.IHttpContextAccessor 接口作为注入接口的参数,改为获取服务方式:
public UserContext(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
var provider = serviceProvider.GetService<IHttpContextAccessor>();
if (provider != null)
{
this.IP = provider.HttpContext.GetClientIP();
}
}