This series is great! It is rare to have information presented at this depth, complete with real issues that come up in production (like the EF issue in vid. 8)! Thank you for sharing your knowledge and contributing in a meaningful way to the democratization of programming!
I have been watching dependency injection videos for many many hours, read a lot of pages, literally gave up that one day i will understand this topic. Then today evening i searched this topic on youtube as a last chance, then found your video and so your channel. Words cannot describe how good your videos are, and finally, I understood everything. You answered all my question came up in the last 2-3 months thinking of this topic. Thank you. Just simply thank you :)
@SingletonSean you have really helped me understand a lot of the concepts of MVVM, abstraction, dependency injection and containers, and many other topics. I'm new to being a professional programmer, and the first job I received I was thrust into a solo developer position creating a relatively large piece of software. Your videos took me from feeling overwhelmed, underqualified, and downright worthless to understanding that the project I've been commissioned to do is possible. Now if you could release a video on how to develop a second set of CBI robotic arms I can code much faster! Thanks again man, your genius is recognized and appreciated.
Hi Sean. your DI videos are really great, but a single one covering only this topic would be great. Now it is necessary to watch two or three videos to get the final result.
That's a good point mcnets! I also implement DI in my current MVVM series, so hopefully that video can be watched on its own. Regardless, this deserves a closer look in it's own video!
Hi Randy, this is a great article on abstraction and how to use dependence injections in general,however, no pun intended, but if you are using these technologies in a large-scale production application like WPF, I would strongly recommend that you look at prism with unity container. Granted that it will be a learning curve but the benefit will out weigh anything you can think of. This episode is a great example of how to use abstraction and information hiding from the implementation and the usage of them through dependency injection. If you follow prism you will have all the facilities and the advantages that this episodes demonstrates but only out of the box in Prism. That would be my humble opinion from practical experience.
Hi, I just found this awsome tutorial. Now I have implemented the video # 10. Now I get the Home window but without content! No Home textbox, no MajorIndexList. I get values for Dow Jones, Nasdaq, S&P 500 but the majorIndexViewModel return Value is null. Do you have an idea?
Nice tutorial series bro. I just wonder one thing... My MainViewModel gets MainWindow into its constructor. I just couldn't figure our how to handle it. Either I have to get MainViewModel type as input in MainWindow then manually set a mainWindow property on MainViewModel, from MainView's constructor. Or i dunno how to solve it :)
Thank you, for some reason all the other videos already start with way too much existing dependency injection & factory pattern code, they already have CreateServiceProvider() and refuse to elaborate further on it
Hi SingletonSean, Thank you for the great tutorial. To understand the dependency injection, I tried to implement a simple project with only a main view model passed by a navigator (without any further implementation or variables). During compilation, an error "No matching constructor found on type 'DepInjectionSimple.MainWindow'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '6' and line position '9'". Can you please suggest me what could be the reason ? If you are unable to understand the issue, I can send my source code.
Great video... There aren't much resources on DI with MVVM Framework. Thank you. Can we use the same approach in UWP .net core desktop application ? And also I have many ViewModels(around 20+). So creating those many factories for view model and passing them in a constructor is feasible ?
Hey Anita, thanks for watching! I've actually never touched UWP before but I would assume that dependency injection is supported since it's part of .NET Core now. The view model factories are a little bit annoying to create, but I think it's the best way to flexibly register services into view models. For simple view models/use cases, I think it's acceptable to just "new" the view model when you need it. For complex view models that require services or have unique lifetimes (ex: should we only use one of this view model type for the entire app?), I think it's better to register the factory.
As I tried this example for dependency injection I got the following error message, when starting the app (no build error occurs): "Unable to resolve service for type 'SimpleTrader.Wpf.State.Navigators.Navigator' while attempting to activate 'SimpleTrader.Wpf.ViewModels.MainViewModel' ". After an hour of searching what I did wrong, I found, that I missed an "I" in "public MainViewModel( Navigator navigator)" Do you have any suggestions makes it easier to find where such an error to find?
That's a tough one Norbert! I think the best way to solve issues like this is to check if the unresolvable service exists in the DI registration. For example, the unresolvable service is the Navigator. This might prompt you to see where Navigator is registered in DI. Upon checking this, you would see that it is registered, but as an INavigator. As a result, the MainViewModel would need to be updated to take an INavigator rather than just a Navigator. That's usually my approach. Of course, it's easier to say what should have been doing after I already know what the correct solution is, hahaha. Regardless, give yourself a pat on the back for debugging and fixing that on your own, learning from your mistake, and even commenting on here for suggestions despite already solving the problem. Your tenacity and drive for knowledge will lead you to success. Best of luck, Norbert!
Thanks tushar! I plan on getting into Web API and ASP.NET in future tutorials, but I would definitely check out Nick Chapsas. His tutorials are great and he has a really good series on Web API.
Great video. I was looking around for a Dependency Injection discussion that wasn't yet another example of a logger service. :) I do have one question. In a prior video for your StockTrader app you commented you were creating a new DB context each time you hit the database because Entity Framework isn't thread safe. Here with dependency injection, you're creating DB context as a singleton to use the same DB context for the life of the application. Can you explain that difference? It's probably something I'm not quite grasping. Thanks!
Hey Mark, thanks for the feedback :) You're correct about the DbContext thread safety and the fact that we need to create a context per database query. However, the dependency injection container registers the DbContext FACTORY, and the factory creates a new DbContext per query.
Hi Sean: GenericDataService - this class does not appear to be referenced in the SimpleTrader app. I have also searched on GitHub. Can you help please?
Hey Ian! Perhaps I recently moved that class. The GenericDataService is located here: github.com/SingletonSean/SimpleTrader/blob/master/SimpleTrader/SimpleTrader.EntityFramework/Services/GenericDataService.cs
On this line of code "return services.BuildServiceProvider" (5:54 mark), I get this error "IServiceCollection does not contain a definition for BuildServiceProvider". Any ideas how this can be fixed? I am using .NET 6.
I do Ian! This is the state of the App.xaml.cs after this video: github.com/SingletonSean/SimpleTrader/blob/662a58dc08652e2a347696c8a5fa69acc4f7c590/SimpleTrader/SimpleTrader.WPF/App.xaml.cs
I totally dislike 2 things here : 1 - The viewmodel factory, where you need to update the code each time you need a new viewmodel 2 - The viewmodel is passed in the windows constructor, in code behind which also require more code when you setup DI My solution is a ViewModelProvider implementation which inherits from MarkupExtension This way you resolve a viewmodel from Xaml directly as usual
I agree Tony! I've moved away from the view model factory for that exact reason. There's really no reason that everything should have to go through a view model factory. If I want 'x' view model, I should just ask for 'x' view model without having to go through a switch statement. I haven't tried the ViewModelProvider MarkupExtension, but I could see how that would work. Do you have a sample of that?
i have an issue with serviceProvider.GetRequiredService when i use serviceProvider.GetRequiredService() as you did with buyStockService it doesn't work but if i Use serviceProvider.GetRequiredService() it does that means if i use the generic interface it throws no service has been registered ....etc but when i use the Implementation it works well , any idea ?
@22:06 "The reason why we're creating factories instead is because I want a different ViewModel everytime that I switch Views. So I can't just register the ViewModel in our dependency injection container, I need to register a factory that will create the ViewModel when I need it." (Edit: Just occurred to me, why not use services.AddTransient()?) What drives me a little batty is that until the ServiceProvider was introduced, the factories weren't needed. And the ServiceProvider was introduced to decouple things that will never be decoupled. I'd argue that someone will want a new ViewModel before one of the services is swapped out. The former has been made much more complicated to make the latter easier, and the latter will likely never happen. I only gripe because it's what I'm dealing with in a project I'm working on. Interfaces and factories are used everywhere and it has created its own form of rigidity.
Hey Hiro, those are good points. In this case, I can't use a transient because the view model is only resolved once, so it will always be the same instance. I understand that in this scenario, DI for view models does appear to make the code more complex. However, without factories, we would need to add all of the services required to instantiate each view model to the root view model factory. This would bloat the constructor and obscure the objects purpose in my opinion. On the downside, it is a pain having to create all those darn factories. Luckily in a future episode, I demonstrate how we can cut out the factories by using delegates, which also ends up allowing us to add view models as transient where applicable. Sadly, I don't quite understand the rigidity that you are experiencing with interfaces/factories. The projects that I run into the most rigidity with are the ones with no interfaces/factories, 500 line functions, and global singletons (my favorite!), and there's no shortage of codebases out there like that, hahaha. As you suggest, perhaps there are different forms of rigidity that are hard to explain. Overall, programming is a complex subject with pros/cons to each approach, and everyone has different opinions based off past experiences. At the end of the day, the code just needs to work and be readable, maintainable, and testable, which is definitely possible without interfaces/factories in some cases.
I think we can turn AbstractFactory into actual Factory. And instead of create so many factory, we just CreateHomeViewMode/CreatePortfiloViewModel in factory. For design in video, we have too many classes and actually they have dependence to each other. I don’t know what i’m thinking is right or not.
Hey menlan, I agree there are too many factories, and the AbstractFactory technically isn't even an abstract factory. I solve both of these issues later by just using delegates and registering them in DI. In my opinion, depending on a delegate is just as flexible as depending on an interface (considering delegates are kind of like interfaces for a single method). Alternatively, you could simply create interfaces and depend on those instead. But then there's more files, but then unit testing would be easier, but do we ever expect to implement the interface differently, but then the code is more flexible?! Hahaha, there are definitely pros and cons to both methods. I feel like the delegates give the best of both worlds.
Thanks! Finished it today. Sorry, but it seems a little overengineering for me. I mean I like IoC and i use it a lot. But in ur case i wouldnt create factories for viewModels and register them in service provider, because i think u will never use or create other implementations of HomeViewModel, for example. So sometimes its ok to create new objects inside code. But other classes u registered is really nice and its 100% right! Thank you:) No hate
Thanks SomeTextHere! I agree it is overengineering from the perspective that I won't switch the view model implementations. However, I still need to register the view models with DI in order to resolve the services that they require. Also, I remove the factories in a future episode because they were a massive pain, haha. Either way, feel free to take this application in any direction you wish. At the end of the day, if it works and it's maintainable, it's a good application. Thanks for the comments!
@@SingletonSean Haha, sorry, maybe better if i say something about code after watching all episodes:) But anyway, you doing great job and its pleasure for me to watch ur videos!
This series is great! It is rare to have information presented at this depth, complete with real issues that come up in production (like the EF issue in vid. 8)! Thank you for sharing your knowledge and contributing in a meaningful way to the democratization of programming!
Thanks Joe! Haha, that was a pretty awesome issue, but that's just the way it goes sometimes.
i know it is kinda randomly asking but does anyone know of a good website to watch newly released tv shows online?
I have been watching dependency injection videos for many many hours, read a lot of pages, literally gave up that one day i will understand this topic.
Then today evening i searched this topic on youtube as a last chance, then found your video and so your channel.
Words cannot describe how good your videos are, and finally, I understood everything. You answered all my question came up in the last 2-3 months thinking of this topic.
Thank you. Just simply thank you :)
That is fantastic news Norbert, I'm glad this video was able to clean everything up! DI can definitely be a confusing topic at first.
This is awesome. The best comprehensive all clear walkthrough I've ever seen or read on this specific subject. Thank you!
Thank you as always, a k!
Wow - this series is the best of WPF I have ever seen!! awesome job - keep it rolling!
Awesome thank you Jan, more on the way!
Thanks for the great work. The best source I found so far for WPF + .Net Core 3.0 + DI
This series is so powerful. I get inspired by the level of your understanding. Thank you so much!
Cool - I like that you take your time to explain, and that you have pop-ups with additional information
This series is exactly what I was looking for... awesome job, Sean :) keep it up!
Thanks Marko, glad you're enjoying!
@SingletonSean you have really helped me understand a lot of the concepts of MVVM, abstraction, dependency injection and containers, and many other topics. I'm new to being a professional programmer, and the first job I received I was thrust into a solo developer position creating a relatively large piece of software. Your videos took me from feeling overwhelmed, underqualified, and downright worthless to understanding that the project I've been commissioned to do is possible. Now if you could release a video on how to develop a second set of CBI robotic arms I can code much faster! Thanks again man, your genius is recognized and appreciated.
That's awesome Bret Bacon! Glad to hear my content has been helpful. Congrats on the developer position as well!
This is a really nice example of how DI should be implemented. Thank you!
superb videos on DI and factory and WPF. Keep up doing . Lots of blessing and love from each one of us.
Glad this was helpful Noor, and thanks for supporting the channel!
I'm loving this series, thank you so much for the awesome work!!
Thanks Marcos, glad you're enjoying!
Best WPF tutorials. Thank!
My friends are binging Netflix, I am binging Singleton Sean :)
Haha thanks Garegin
@@SingletonSean Thank you, the value that this series provides is insane! I cannot believe that this exists.
Hi Sean. your DI videos are really great, but a single one covering only this topic would be great. Now it is necessary to watch two or three videos to get the final result.
That's a good point mcnets! I also implement DI in my current MVVM series, so hopefully that video can be watched on its own. Regardless, this deserves a closer look in it's own video!
Is dependency injection a good option for building large scale desktop applications (wpf, winforms)?
I think it is an essential piece of an application Randy. I'm so obsessed with DI that I unnecessarily use it for small apps too, haha.
Hi Randy, this is a great article on abstraction and how to use dependence injections in general,however, no pun intended, but if you are using these technologies in a large-scale production application like WPF, I would strongly recommend that you look at prism with unity container. Granted that it will be a learning curve but the benefit will out weigh anything you can think of. This episode is a great example of how to use abstraction and information hiding from the implementation and the usage of them through dependency injection. If you follow prism you will have all the facilities and the advantages that this episodes demonstrates but only out of the box in Prism. That would be my humble opinion from practical experience.
Hi, I just found this awsome tutorial. Now I have implemented the video # 10. Now I get the Home window but without content! No Home textbox, no MajorIndexList. I get values for Dow Jones, Nasdaq, S&P 500 but the majorIndexViewModel return Value is null. Do you have an idea?
Hi,
Just found the error !
In public class MainViewModel : ViewModelBase
public INavigator Navigator { get; set; }
Thanks Klaus, glad you were able to resolve that!
Nice tutorial series bro. I just wonder one thing... My MainViewModel gets MainWindow into its constructor. I just couldn't figure our how to handle it. Either I have to get MainViewModel type as input in MainWindow then manually set a mainWindow property on MainViewModel, from MainView's constructor. Or i dunno how to solve it :)
Thank you, for some reason all the other videos already start with way too much existing dependency injection & factory pattern code, they already have CreateServiceProvider() and refuse to elaborate further on it
Hi SingletonSean,
Thank you for the great tutorial.
To understand the dependency injection, I tried to implement a simple project with only a main view model passed by a navigator (without any further implementation or variables). During compilation, an error "No matching constructor found on type 'DepInjectionSimple.MainWindow'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '6' and line position '9'". Can you please suggest me what could be the reason ? If you are unable to understand the issue, I can send my source code.
Great video... There aren't much resources on DI with MVVM Framework. Thank you.
Can we use the same approach in UWP .net core desktop application ? And also I have many ViewModels(around 20+). So creating those many factories for view model and passing them in a constructor is feasible ?
Hey Anita, thanks for watching! I've actually never touched UWP before but I would assume that dependency injection is supported since it's part of .NET Core now. The view model factories are a little bit annoying to create, but I think it's the best way to flexibly register services into view models. For simple view models/use cases, I think it's acceptable to just "new" the view model when you need it. For complex view models that require services or have unique lifetimes (ex: should we only use one of this view model type for the entire app?), I think it's better to register the factory.
thank you so much, I feel the INavigator is Singleton
I agree with the comments below. Excellent!
Thank you for video! How binding ViewModel in View?
As I tried this example for dependency injection I got the following error message, when starting the app (no build error occurs):
"Unable to resolve service for type 'SimpleTrader.Wpf.State.Navigators.Navigator' while attempting to activate 'SimpleTrader.Wpf.ViewModels.MainViewModel' ".
After an hour of searching what I did wrong, I found, that I missed an "I" in "public MainViewModel( Navigator navigator)"
Do you have any suggestions makes it easier to find where such an error to find?
That's a tough one Norbert! I think the best way to solve issues like this is to check if the unresolvable service exists in the DI registration. For example, the unresolvable service is the Navigator. This might prompt you to see where Navigator is registered in DI. Upon checking this, you would see that it is registered, but as an INavigator. As a result, the MainViewModel would need to be updated to take an INavigator rather than just a Navigator.
That's usually my approach. Of course, it's easier to say what should have been doing after I already know what the correct solution is, hahaha. Regardless, give yourself a pat on the back for debugging and fixing that on your own, learning from your mistake, and even commenting on here for suggestions despite already solving the problem. Your tenacity and drive for knowledge will lead you to success. Best of luck, Norbert!
Hello! Love the videos. Best so far for wpf. Can you suggest any channel for web api in .net core as well.
Thanks tushar! I plan on getting into Web API and ASP.NET in future tutorials, but I would definitely check out Nick Chapsas. His tutorials are great and he has a really good series on Web API.
Great video. I was looking around for a Dependency Injection discussion that wasn't yet another example of a logger service. :) I do have one question. In a prior video for your StockTrader app you commented you were creating a new DB context each time you hit the database because Entity Framework isn't thread safe. Here with dependency injection, you're creating DB context as a singleton to use the same DB context for the life of the application. Can you explain that difference? It's probably something I'm not quite grasping. Thanks!
Hey Mark, thanks for the feedback :) You're correct about the DbContext thread safety and the fact that we need to create a context per database query. However, the dependency injection container registers the DbContext FACTORY, and the factory creates a new DbContext per query.
@@SingletonSean oh duh, right, thanks!
Hi Sean: GenericDataService - this class does not appear to be referenced in the SimpleTrader app. I have also searched on GitHub. Can you help please?
Hey Ian! Perhaps I recently moved that class. The GenericDataService is located here: github.com/SingletonSean/SimpleTrader/blob/master/SimpleTrader/SimpleTrader.EntityFramework/Services/GenericDataService.cs
you rock
On this line of code "return services.BuildServiceProvider" (5:54 mark), I get this error "IServiceCollection does not contain a definition for BuildServiceProvider". Any ideas how this can be fixed? I am using .NET 6.
Hey Code Match! I haven't used .NET 6 yet, but do you have Microsoft.Extensions.DependencyInjection installed?
@@SingletonSean Thanks a lot for the reply SingletonSean. That worked! Keep up the great work.
Do you have the intermediate code please, i.e. before the Dependency Injection is "cleaned up" in a later episode?
I do Ian! This is the state of the App.xaml.cs after this video: github.com/SingletonSean/SimpleTrader/blob/662a58dc08652e2a347696c8a5fa69acc4f7c590/SimpleTrader/SimpleTrader.WPF/App.xaml.cs
@@SingletonSean Many thanks for that Sean- a great help.
I totally dislike 2 things here :
1 - The viewmodel factory, where you need to update the code each time you need a new viewmodel
2 - The viewmodel is passed in the windows constructor, in code behind which also require more code when you setup DI
My solution is a ViewModelProvider implementation which inherits from MarkupExtension
This way you resolve a viewmodel from Xaml directly as usual
I agree Tony! I've moved away from the view model factory for that exact reason. There's really no reason that everything should have to go through a view model factory. If I want 'x' view model, I should just ask for 'x' view model without having to go through a switch statement.
I haven't tried the ViewModelProvider MarkupExtension, but I could see how that would work. Do you have a sample of that?
excellent!!!!
i have an issue with serviceProvider.GetRequiredService
when i use serviceProvider.GetRequiredService() as you did with buyStockService it doesn't work but if i Use serviceProvider.GetRequiredService() it does
that means if i use the generic interface it throws no service has been registered ....etc but when i use the Implementation it works well , any idea ?
Interesting issue The Engineer-Development. Have you registered the GenericDataService to an IDataService? ex: services.AddSingleton()
@@SingletonSean yeah this's what i did
@@SingletonSean well , now it works, it seams that i missed some code ! thank you
Hooray!
@22:06 "The reason why we're creating factories instead is because I want a different ViewModel everytime that I switch Views. So I can't just register the ViewModel in our dependency injection container, I need to register a factory that will create the ViewModel when I need it."
(Edit: Just occurred to me, why not use services.AddTransient()?)
What drives me a little batty is that until the ServiceProvider was introduced, the factories weren't needed. And the ServiceProvider was introduced to decouple things that will never be decoupled. I'd argue that someone will want a new ViewModel before one of the services is swapped out. The former has been made much more complicated to make the latter easier, and the latter will likely never happen.
I only gripe because it's what I'm dealing with in a project I'm working on. Interfaces and factories are used everywhere and it has created its own form of rigidity.
Hey Hiro, those are good points. In this case, I can't use a transient because the view model is only resolved once, so it will always be the same instance. I understand that in this scenario, DI for view models does appear to make the code more complex. However, without factories, we would need to add all of the services required to instantiate each view model to the root view model factory. This would bloat the constructor and obscure the objects purpose in my opinion. On the downside, it is a pain having to create all those darn factories. Luckily in a future episode, I demonstrate how we can cut out the factories by using delegates, which also ends up allowing us to add view models as transient where applicable. Sadly, I don't quite understand the rigidity that you are experiencing with interfaces/factories. The projects that I run into the most rigidity with are the ones with no interfaces/factories, 500 line functions, and global singletons (my favorite!), and there's no shortage of codebases out there like that, hahaha. As you suggest, perhaps there are different forms of rigidity that are hard to explain. Overall, programming is a complex subject with pros/cons to each approach, and everyone has different opinions based off past experiences. At the end of the day, the code just needs to work and be readable, maintainable, and testable, which is definitely possible without interfaces/factories in some cases.
Thank you so much
but what about auofac.
I think we can turn AbstractFactory into actual Factory. And instead of create so many factory, we just CreateHomeViewMode/CreatePortfiloViewModel in factory. For design in video, we have too many classes and actually they have dependence to each other. I don’t know what i’m thinking is right or not.
Hey menlan, I agree there are too many factories, and the AbstractFactory technically isn't even an abstract factory. I solve both of these issues later by just using delegates and registering them in DI. In my opinion, depending on a delegate is just as flexible as depending on an interface (considering delegates are kind of like interfaces for a single method). Alternatively, you could simply create interfaces and depend on those instead. But then there's more files, but then unit testing would be easier, but do we ever expect to implement the interface differently, but then the code is more flexible?! Hahaha, there are definitely pros and cons to both methods. I feel like the delegates give the best of both worlds.
8:20 very important
Thanks! Finished it today. Sorry, but it seems a little overengineering for me. I mean I like IoC and i use it a lot. But in ur case i wouldnt create factories for viewModels and register them in service provider, because i think u will never use or create other implementations of HomeViewModel, for example. So sometimes its ok to create new objects inside code. But other classes u registered is really nice and its 100% right! Thank you:) No hate
Thanks SomeTextHere! I agree it is overengineering from the perspective that I won't switch the view model implementations. However, I still need to register the view models with DI in order to resolve the services that they require. Also, I remove the factories in a future episode because they were a massive pain, haha. Either way, feel free to take this application in any direction you wish. At the end of the day, if it works and it's maintainable, it's a good application. Thanks for the comments!
@@SingletonSean Haha, sorry, maybe better if i say something about code after watching all episodes:) But anyway, you doing great job and its pleasure for me to watch ur videos!
Making a shit-ton of factories like that seems like a code-smell.
Dude !!!