Home > Mobile >  System.InvalidOperationException: Unable to resolve service in ASP.NET Core
System.InvalidOperationException: Unable to resolve service in ASP.NET Core

Time:12-29

I am a beginner in ASP.NET Core. I am creating a Web API service. While I am fetching the data from the database, I had a problem. What is the error I got? I have successfully done the database migration part and created the database successfully.

System.InvalidOperationException: Unable to resolve service for type 'webb.StudentDbContext' while attempting to activate 'webb.Controllers.StudentController'.

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method3(Closure , IServiceProvider , Object[] )

StudentController:

[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
    private StudentDbContext studentDbContext;

    public StudentController(StudentDbContext studentDbContext)
    {
        studentDbContext = studentDbContext;
    }

    // GET: api/<EmployeeController>
    [HttpGet]
    public IEnumerable<Student> Get()
    {
        return studentDbContext.Student;
    }
}

Model class:

namespace webb.Model
{
    public class Student
    {
        public int id { get; set; }
        public int stname { get; set; }

        public int course { get; set; }
    }
}

StudentDbContext:

 public class StudentDbContext : DbContext
 {
     public DbSet<Student> Student { get; set; }

     public StudentDbContext()
     {
     }

     public StudentDbContext(DbContextOptions options) : base(options)
     {
     }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Student>().HasKey(e => e.id);
     }

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
     {
         optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=sms;Integrated Security=True; TrustServerCertificate = True");
     }
}

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "StudentConnStr": "Data Source=.;Initial Catalog=sms;Integrated Security=True;"
  }
}

Where I am going to set the key.

Program.cs:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using webb;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

builder.Services.AddDbContext<StudentDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")));

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

CodePudding user response:

Look like you are missing out inject StudentDbContext which is the DbContext to DI container.

Add below to your Program.cs:

builder.Services.AddDbContext<StudentDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));

refer to this and Part 5, work with a database in an ASP.NET Core MVC app

Update

builder.Services.AddDbContext<StudentDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));

var app = builder.Build();

CodePudding user response:

builder.Build() should be after all AddXXX functions. In other words, you need to swap it with AddDbContext()

builder.Services.AddDbContext<StudentDbContext>(options =>
 options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")));

var app = builder.Build();

  • Related