C
C#2y ago
Messiah

❔ How DI works?

Been using dependency injection to share variables between classes a lot lately, and it got me wondering how does it work? Why are they able to access eachother's variables just because they share an interface? Using ASP.NET and more specifically HttpClient
14 Replies
phaseshift
phaseshift2y ago
Wdym 'each others variables'? You can only expose properties and methods via interfaces
Messiah
MessiahOP2y ago
that's what I thought, interfaces had no logic in it, but then you look at httpclients within asp.net if you do builder.AddHttpClient("named"), you get the reference to said client no matter where in the code
phaseshift
phaseshift2y ago
When you inject the client via constructor, you mean?
Messiah
MessiahOP2y ago
yeah
phaseshift
phaseshift2y ago
So what's confusing?
Messiah
MessiahOP2y ago
it makes 0 sense, you inject an interface (which by convention has no implementation)
phaseshift
phaseshift2y ago
No, the interface gets registered in the container with an implementation When the interface is'requested' via a ctor, then the container makes the implementation and injects it
Messiah
MessiahOP2y ago
that makes sense, but why are we calling methods on the "interface" (which isn't gonna be an interface at runtime I assume), when the programming rules state that you can't call an interface directly? I get that we're using the interface's guidelines, but in the IDE we're still calling the interface as if it was a real class with real code in it
phaseshift
phaseshift2y ago
That's kinda the point of interfaces
Messiah
MessiahOP2y ago
interesting so when a class inherits an interface, you can put the interface as parameter, and the IDE won't complain?
phaseshift
phaseshift2y ago
Classes don't really inherit interfaces. They implement them. But yes You can then pass instances of that class into any param of the interface type C# doesn't support multiple inheritance
Messiah
MessiahOP2y ago
Interesting, finally understanding things, thanks Does builder.Services.AddSingleton<A, B> work similarly? You need to pass A as the interface, and B for the actual implementation?
phaseshift
phaseshift2y ago
Yes
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server