DEV Community

Cover image for How YOU can Learn Dependency Injection in .NET Core and C#

How YOU can Learn Dependency Injection in .NET Core and C#

Chris Noring on November 28, 2019

Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris This is an intro to Dependency Injection, also called DI. I ...
Collapse
 
alirezamgh profile image
alireza

Hi Chris.
Excellent Post. Thank you.
I have a question => you mentioned " it makes sense to use when you have a mutable state and it's important that the service consumer gets their own copy of this service." can you explain what that means and also explain how that work with other scopes like Scoped and Singleton ?

Collapse
 
softchris profile image
Chris Noring

hey.. so the whole idea of DI, at least in my mind is about three things 1) reuse services that are expensive to create 2) be able to share state. 3) make testing easier/code needs modification less seldom, you rely on contracts, i.e Interfaces Singleton pattern is a clear case where we can share state. Because it's created only once, you have fields on that service that you write to, e.g a CartService can be a singleton with an Items fields that you can keep adding items to and you can ensure that there are no more than one CartService created

Collapse
 
pmbanugo profile image
Peter Mbanugo

Thanks for the article. The last link at the beginning routes to a 404 pages.

Collapse
 
softchris profile image
Chris Noring

hi Peter. Thanks for that. The link should be fixed now

Collapse
 
dolomike profile image
Michael Roberts • Edited

Loved the article! I found a small typo for correction in the controller:

private readonly _shippingService IShippingService;

Collapse
 
softchris profile image
Chris Noring

Thanks, Michael, glad you liked it. Appreciate the typo correction as well :)

Collapse
 
hadagali profile image
hadagali

Wonderful article on dependency injection

Just a small question?
The heading says
Create an interface IProductsController
And the code actually created is IProductService, it the heading a typo?

Collapse
 
softchris profile image
Chris Noring

yes it was, thank you :)

Collapse
 
danharries profile image
Dan Harries

Hi Chris,

Great article, good refresher!

Collapse
 
softchris profile image
Chris Noring

Thank you for that Jeffrey :)

Collapse
 
theadin profile image
theadin • Edited

Seriously, First article that finally got me to understand Dependency Injection!

(BTW, you need to fix your 'e' key. It's missing in many places. Are you using one of those Mac laptops?)

Collapse
 
softchris profile image
Chris Noring

thanks. and yes my Mac has seen better days :)