无法在Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider

时间:2019-01-03 13:00:01

标签: asp.net-core

我正在尝试从服务器控制器(库存)接收数据。

我收到此错误:

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

这是我的股票控制者代码:

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             services.AddScoped();

1 个答案:

答案 0 :(得分:1)

问题是数据库上下文未注册用于依赖项注入。

添加:

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

解决了该问题。