Reputation: 15
I couldnt quite grasp the readonly and the CategoryController constructor here, what is the necessity of private readonly constructor and assigning _db = db. My ApplicationDbContext class inherits from EF Dbcontext class and the options parameter is passed to the base class, what does this private readonly and the constructor do here and whats its necessity? Image link : https://i.sstatic.net/oW8Zg.png
public class CategoryController : Controller
{
private readonly ApplicationDbContext _db;
public CategoryController(ApplicationDbContext db)
{
_db = db;
}
Upvotes: 1
Views: 958
Reputation: 197
The concept is called Dependency Injection, you can read more about it here.
Basically, you're injecting the database context. You can create it in your class like var context = new ApplicationDbContext()
, but the class becomes dependent on this exact implementation. In the future you might want to use other contexts (like MongoDbContext
or something), but it won't be possible to pass them to this class cause they're of different types.
To solve it, you make all your contexts implement inteface (IMyContext
for example), create readonly IMyContext
field in your class and pass whatever you need in constructor.
Upvotes: 4