C
C#5d ago
reeeeeee

When to use Dependency injection?

I am learning WPF and since I am used to work with DI almost always in my previous projects (mostly APIs) I am not sure if I need it. Is using DI in wpf really best practice? My app is currently not really complicated, I only have some kind of Get data from API and save to db. Is DI recommended in this case? or does wpf have any special "best practices" what should you work with?
4 Replies
friedice
friedice5d ago
DI makes unit testing 100x easier and makes your code more modular. Personally haven't worked with WPF much, but I believe in the motto of use it as you need it.
Furtun
Furtun5d ago
WPF doesn't have in-built support for DI, but you can find libraries online that add DI over it. Personally I'd use DI wherever I can. As @IceGPT said, it's just cleaner. It makes testing easier. It makes it much easier to maintain separate modules. Also it makes it much easier to track dependencies. And finally, it allows you to better control lifetimes of services, eg. Transient, Scoped, Singleton. You can define them in one place and your dependencies don't need to care that your db connector is a singleton, or your w/e else dependency is a transient dependency, etc.
reeeeeee
reeeeeee4d ago
yeag i have to use Microsoft.Extensions.DependencyInjection; so i guess its fine, becausei ts not some kind of 3rd party library
Cliff Choongo
Cliff Choongo3d ago
To understand whether you should use DI (Dependency Injection) or not you should first ask yourself and understand these three questions.What is DI? What is it used for? And what it's purpose or role? And then you will have a clear mind whether to use it not.DI makes your code to be more testable and maintainable.DI also has other benefits like it enables you to create an instance of an interface and that also applies to classes.
Want results from more Discord servers?
Add your server