skip to Main Content

I Got an error while creating controller using scaffolding "Unable to resolve service for type, while attempting to activate ‘MyWebApplication.Models.MyDbContext’ "Here is the image of my code and error while creating controller using scaffolding

I want a solution of my problem and I tried everything but unable to resolve. Here is the image of my code and error while creating controller using scaffolding

2

Answers


  1. Please provide more information so that we can help you out. To me, it sounds like you have not registered the DbContext with your Dependency Injection and that’s why it could not be "activated".

    Check if your context is registered with the DI first. If that does not make the trick, provide more information.

    You can register the context by doing something like:

        services.addDbContext<ApplicationDbContext>((sp, options) => {
            var cnstring = 
      sp.GetRequiredService(IConfiguration).GetConnectionString("default");
        options.UseSqlServer(cnstring);
        });
    
    Login or Signup to reply.
  2. Based on the error screenshot you provided, I replicated the issue Unable to resolve service for type, while attempting to activate ‘MyWebApplication.Models.MyDbContext’, The issue relates that the DbContext is not registered when using the scaffolding.
    My model:

     public class Students
      {
          public int Id { get; set; }
          public string? Genre { get; set; }
          public string? Name { get; set; }
      }
    

    My Dbcontext:

    public class MyDbcontext : DbContext
        {
            public MyDbcontext(DbContextOptions<MyDbcontext> options) : base(options)
            {
            }
    
            public DbSet<Student> students { get; set; }
        }
    

    When I didn’t register MyDbcontext in ConfigureServices:

    enter image description here

    The same problem occurs as depicted in the figure:

    enter image description here

    When I registered Mydbcontex with ConfigureServices in Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddDbContext<MyDbcontext>(options =>
                    options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbcontext")));
    

    The StudentsController be created successfully:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search