0

This is a question about how ASP.NET MVC is working. Now I am trying to understand how the controller pass data from database. And I cannot see where "context" comes from to the args[0] of the constructor in a scaffoled controller. For example, when you scaffolds a controller from a model called "item", you get ItemsController. The constructor of StaffsConroller goe like;

public ItemsController(DbContext context) { _context = context } 

The variable "_context" is declared in ItemsController. But where is "context" instanced?

1

2 Answers 2

1

If you use Entity Framework or configure dependency injection in Startup.cs, then DbContext is created by Dependency Injection. You can research consturctor injection.

ASP.NET Core applications are configured using dependency injection. EF Core can be added to this configuration using AddDbContext in the ConfigureServices method of Startup.cs. For example:

public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContext<ApplicationDbContext>( options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection")); } 

For more details you can visit these links: DbContext in dependency injection for ASP.NET Core, Dependency injection in the controller

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. In the visual studio local window , I found the context is add as a service in the service collection. Can I say that the entity is not eatablished at this timing?
1

DbContext is Injected into the constructor via Dependency Injection.

When the ItemsController is created (usually every time a new HTTP request arrives at a route mapped to an ItemsController action) the ASP.NET engine knows that ItemsController needs a DbContext and it instantiates a new DbContext there.

See more here: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-5.0&tabs=visual-studio#dependency-injection-in-the-controller

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.