gpt4 book ai didi

asp.net-core - 无法解析 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider) 类型的服务

转载 作者:行者123 更新时间:2023-12-05 03:03:26 27 4
gpt4 key购买 nike

我正在尝试从服务器 Controller 接收数据,stocks。

我收到这个错误:

“System.InvalidOperationException:在尝试激活“myBackEnd.Controllers.StockController”时无法解析 myBackEnd.Models.StockContext 类型的服务。 在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService (IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired”

这是我的股票 Controller 代码:

namespace myBackEnd.Controllers
{
[Route("api/stock")]
[Produces("application/json")]

public class StockController : ControllerBase
{
private readonly int fastEmaPeriod = 10;

private readonly IHttpClientFactory _httpClientFactory;
private readonly Models.StockContext _context;

public StockController(Models.StockContext context, IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
_context = context;
}

// POST api/values
[HttpPost]
public async Task<IActionResult> Post([FromBody]Models.Stock stock)
{
_context.Stocks.Add(stock);
await _context.SaveChangesAsync();
return Ok(stock);
}

这是 startup.cs 代码:

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", corsBuilder =>
{
corsBuilder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));

services.AddDbContext<DataContext>(x => x.UseInMemoryDatabase("TestDb"));
services.AddHttpClient();
services.AddAutoMapper();

// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);

// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var userId = int.Parse(context.Principal.Identity.Name);
var user = userService.GetById(userId);
if (user == null)
{
// return unauthorized if user no longer exists
context.Fail("Unauthorized");
}
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});

// configure DI for application services
services.AddScoped<IUserService, UserService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


}

这在我添加注册、登录和

之前有效

//为应用服务配置DI 服务.AddScoped();

最佳答案

问题是数据库上下文没有为依赖注入(inject)注册。

添加:

services.AddDbContext<Models.StockContext>(opt => opt.UseInMemoryDatabase("item"));

解决了这个问题。

关于asp.net-core - 无法解析 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider) 类型的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54022810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com