✅ meaning on dependency injection in C#
Hello guys, I was just reading a bit, I came across those terms "dependency injection". Can someone explain what this mean please. I read a bit about it, what I read is that dependency injection is used to prevent "tight coupling" (don't know what this is). Is dependency injection same as when we are importing libraries, like .NET libraries?
Would really appreciate if someone can give simple code example of with and without dependency injection of what happen
8 Replies
Simple example (not actual code)
It lets you do a few things:
1. Control the lifetime of the dependencies (per instance, per request, per app run, etc)
2. Swap the dependencies freely (change that
<IMailer, GmailMailer>
to <IMailer, ProtonMailMailer>
and everything that requests IMailer
will use ProtonMailMailer
now)Dependency injection - .NET
Learn how to use dependency injection within your .NET apps. Discover how to registration services, define service lifetimes, and express dependencies in C#.
"Loose coupling" here means that
ThingyDoer
does not create its own new GmailMailer()
, but rather is given an already existing instance of it
Or an instance of any other IMailer
Is it correct to say that the idea of using dependencing injection is that instead of a class creating a specific instance of a class, assume we have 2 classes, student and person. if we have class person, instead of directly creating an instance of class student inside person (let say we require student to do stuff on it) , we want a way to make this "student" type more flexible in case we no longer want a student but rather another instance type?
by the way, here, a dependency means an instance of a class?
let say we have 3 classes, teacher, student and person.
if in main, we write the following:
This is dependency injection ?
dependency injection itself just means passing objects that a new object needs to function in its constructor, so yes
this moves the responsibility of "knowing" what types of objects to use from the new object to the code creating it
yeah I see, was what I said correct pls
Hey @Faker
I see you're on quite the learning journey from all your posts. If you want to read more about DI, I can highly recommend this book:
https://www.oreilly.com/library/view/dependency-injection-principles/9781617294730/
It is in my opinion one of the best books any dotnet (or OOP in general) developer should read.
O’Reilly Online Learning
Dependency Injection Principles, Practices, and Patterns
yep I will have a look, thanks !