0

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();
6
  • What's your startup.cs looks like ? How you register the dbcontext? Commented Dec 29, 2022 at 5:19
  • i didn't add the startup.cs Commented Dec 29, 2022 at 5:24
  • You have the Program.cs? Commented Dec 29, 2022 at 5:25
  • yes............................. Commented Dec 29, 2022 at 5:25
  • why this error is displayed Commented Dec 29, 2022 at 5:26

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

13 Comments

builder.Configuration this line getting error
@abi jega What's error you get ?
Configuration is not null here
@abi jega Could you refer Part 5, work with a database in an ASP.NET Core MVC app to set your ConectionString key from appsettings.json ?
i attached the appsettings.json where i going to set the key
|
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.