r/learnprogramming • u/Bofact • 28d ago
Tutorial Dependency Injection confusing example
I am learning about Dependency Injection from the below link Dependency Injection in ASP comma NET MVC Tutorial | ASSIST Software, but in the first example is writing a prototype, in the second it creates "a separate class that has the responsibility of working with the database", but no class is created. He only implements the function from the example 1.
Am I missing something?
Edit: I initially put a link to the tutorial in question, but Reddit removed my post. So this is why this post doesn't have a link.
11
Upvotes
6
u/SwiftQuest 28d ago
I can't see the exact tutorial, but a common thing in DI intros is that the database class itself isn't the point. The point is that your controller stops creating it with new and instead asks for it through its constructor, usually typed as an interface. So the example you're describing probably has an interface with the method signatures (the "prototype"), and the real class that talks to the database just gets assumed or left out to keep the example short. The separate class would be whatever implements that interface, and you tell the framework in Program.cs or Startup which implementation to hand out. The payoff is that the controller only knows about the interface, so you can swap in a fake one for tests or change the database code later without touching the controller. If you try writing a small class that implements the interface yourself and registers it, it tends to click pretty fast.
2
u/TheStonedEdge 28d ago
When I was learning DI what helped the most was
2
u/Upstairs-Project2756 27d ago
you are not missing anything, the tutorial is just being lazy. The concrete database class likely already exists in their full codebase but wasn't shown to save space. You don't need a new separate class if you already have one working; you just change how the controller gets it. Replace `new DatabaseClass()` with `public Controller(IDatabase _db) { _db = ... }`. That is the actual DI step they skipped writing out
1
u/DrDesperate 28d ago
tutorials do this a lot, they show the interface and then wave at the db class like it already exists. the whole trick is the controller gets handed the thing instead of building it itself, so you could swap in a fake one for testing.