❔ 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
Wdym 'each others variables'?
You can only expose properties and methods via interfaces
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
When you inject the client via constructor, you mean?
yeah
So what's confusing?
it makes 0 sense, you inject an interface (which by convention has no implementation)
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
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
That's kinda the point of interfaces
interesting
so when a class inherits an interface, you can put the interface as parameter, and the IDE won't complain?
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
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?Yes
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.