3

I am attempting to receive data from the server controller, stocks.

I get this error:

"System.InvalidOperationException: Unable to resolve service for type myBackEnd.Models.StockContext' while attempting to activate 'myBackEnd.Controllers.StockController'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService (IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired"

Here is my stocks controller code:

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);
    }

This is the startup.cs code:

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);


    }

This worked before I added the registration, login and

// configure DI for application services services.AddScoped();

4
  • The error seems fairly clear. DI is trying to find a service of type StockContext and it can't. I see you have registered a DataContext, but I don't see the StockContext being registered.
    – juunas
    Jan 3, 2019 at 13:02
  • Thanks for the answer. I added "services.AddDbContext<Models.StockContext>(opt => opt.UseInMemoryDatabase("item"));
    – Lee9287
    Jan 3, 2019 at 13:53
  • And did that fix it? :)
    – juunas
    Jan 3, 2019 at 13:54
  • yes! It fixed it. Breezing along. I am new at this, My first app. Loving it so far
    – Lee9287
    Jan 3, 2019 at 13:59

1 Answer 1

4

The problem was the DB context was not registered for dependency injection.

Adding:

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

fixed the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.