Reputation: 59
I'm new to C#, and when i opened the Controller of a MVC project(ASP.NET), i have found the following syntax:
public class CategoriasController : Controller
{
private readonly ApplicationDbContext _context;
public CategoriasController(ApplicationDbContext context)
{
_context = context;
}
I'm sorry to ask, but what's happening on line 3?
private readonly ApplicationDbContext _context;
Is _context
a variable? An object? That's the same of saying _context = new ApplicationDbContext
?
Sorry for the question, I've searched the Microsoft docs, but couldn't find any answer.
Upvotes: 1
Views: 870
Reputation: 82337
The MVC model as a whole when implemented in C# is a little interesting, but does work very well.
When a request is made, the path of the request is used by the routing mechanism to use reflection to instantiate a class capable of handling the response.
In this case, when a matching ActionResult method name matching the CategoriasController class name, for example /Categorias/Fiction is used, then the matching controller class will be instantiated via reflection.
Once the class is instantiated, the method is called. During class instantiation, normal things occur that occur with any other class. So, what you see here, is the availability of a class level member _context
. Looking further, you can see that there is a constructor which can be called with a context as well. That is known as inversion of control, and is accomplished with a dependency injection container. This means that during the instantiation from reflection, a fully instantiated context (for querying a database) is also created and then passed in. In MVC the DI container is often defined in the global.asax.cs file.
Once the class is instantiated, and the member method called, the return view essentially creates a string writer to be written to the response stream, and MVC's job is done.
Upvotes: 1
Reputation: 5550
This ensures that the class level variable _context
can only be set in the constructor and cannot otherwise be changed. In the context of accessing a database as here you do not want the class methods to be able to change this, only to use.
The the c# documentation for readonly
here it states "In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class."
Upvotes: 1