0

I got the error when initialize the dbModel context as follows:

enter image description here

This is my dbContext class:

public class DbModel : DbContext
{
    public DbModel()
    {
    }

    public DbModel(DbContextOptions<DbModel> options)
        : base(options)
    { }

    public DbSet<UserModel> User {get;set;}
}

I added the following code in the ConfigureServices method in Startup.cs according to some answers in stackoverflow, but I'm still getting an error.

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

This is my ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
        services.AddMvc();
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.Restaurant;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<DbModel>(options => options.UseSqlServer(connection));
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "Restaurant APIs", Description = "Swagger Core API" });
        });
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    }

What could be the reason?

2 Answers 2

1

You're manually initializing DbModel instead of using DI to inject it into your controller.

public ValuesController : Controller
{
    private readonly DbModel _db;

    public ValuesController(DbModel db)
    {
        _db = db;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

The above answer is correct.DbContext initialization needs to inject dependencies from the container.So you can't directly use new.

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.