Dependency Injection, Generic Host, and WPF

  Рет қаралды 6,745

Kevin Bost

Kevin Bost

Күн бұрын

In this video we will take a look at using the Generic Host for providing dependency injection for a WPF app.
Repository: github.com/Keboo/ColorKraken
Generic Host: docs.microsoft.com/dotnet/cor...
Dependency Injection: docs.microsoft.com/dotnet/cor...
Broadcasted live on Twitch -- Watch live at twitch.keboo.dev

Пікірлер: 22
@nicolaihenriksen6625
@nicolaihenriksen6625 2 жыл бұрын
Awesome stuff! I really like the way you manage to explain things so they are easy to grasp; something that is often not as easy when just reading about it on your own. I have worked with WPF apps (MVVM) and used dependency injection principles on a number of projects, but I am relatively new in combining the two things. This video was great and provided me with some of the missing pieces! Thanks a lot for that!! I am still, however, left a bit puzzled when it comes to solving some things. The list below highlights the struggles I am currently facing and need some guidance on. I hope you are willing to share a bit more of your wisdom and time. 1. What is the best practice when it comes to injecting runtime data (alongside registered services) into the DI created types (e.g. ViewModels)? Currently I am using the factory pattern, but I still feel like I am missing a key point somewhere. I end up with temporal coupling because the DI container cannot (and probably should not) resolve my runtime data. 2. Scope management; easy to grasp with the simple samples where everything is encapsulated in a using block. How would one go about managing "longer living" scopes (i.e. using block not feasible)? In my examples below, how would I go about letting each tab live in its own scope while still following DI principles and best practices. 3. "Nested ViewModels"; if I have a complex UserControl for which I want a dedicated ViewModel, when I then add that UserControl to the MainWindow.xaml which has a MainWindowViewModel, how do I go about getting the right view model for the View while still following the DI principles? Should one MainWindowViewModel simply have a MyUserControlViewModel injected via the ctor and expose it as a property? This does not feel completely right to me... For bullets 1 and 2 I have created a repository which illustrates my struggles. The essence of the struggles are captured in this Gist: gist.github.com/nicolaihenriksen/12461b3f47aa86b07a75202adf0d6d4b The full repo can be found on the link below. It is a simple WPF "browser-like" application which can open/close tabs. Tabs just contain some text and a button to close the tab again: github.com/nicolaihenriksen/WpfBrowser For bullet 3, I have not (yet) included an example in the repo, but I hope the description is clear enough. I know this may be a lot of stuff for you to consider, and as such I don't expect you to answer it all. I hope you can guide me in the right direction. Perhaps you could use this for a topic for one of your future streams even? Again, thanks for all the great content, I love watching and learning stuff.
@Kitokeboo
@Kitokeboo 2 жыл бұрын
These are really great questions! I decided to go through them live on my stream last night. I will be posted to KZbin here (kzbin.info/www/bejne/l3rYq4ydlJWhl9U) on Monday, or you can catch the recording of the live stream at: twitch.keboo.dev.
@mateuszchrupczalski4247
@mateuszchrupczalski4247 2 жыл бұрын
Great stuff, learned more in an hour than through a week doing my own research. I love the fact that you are explaining concepts which could be considered basic for people who's been doing coding for some time, a lot of other videos on yt, is more like "muahh, everyone knows that" No! We don't. Great content, keep it up!
@williamliu8985
@williamliu8985 2 жыл бұрын
The delegate creator with DI, instead of traditional factory mode . What a genius!!
@Zuljhin
@Zuljhin 2 жыл бұрын
Edit: Great stuff, please never stop. We're in different time zones so I can never catch you live. But your videos are very interesting and helpful.
@sergeys5270
@sergeys5270 2 жыл бұрын
Excellent video!
@amro6838
@amro6838 2 жыл бұрын
Great video
@yonggheelim1934
@yonggheelim1934 9 ай бұрын
Great video. Thanks so much. I look forward to seeing a youtube on AutoDI if possible.
@Kitokeboo
@Kitokeboo 9 ай бұрын
Thank you for the kind words. I am planning on redoing the way AutoDI functions to take advantage of newer C# features and plan to do a video on it when it is ready.
@yonggheelim1934
@yonggheelim1934 9 ай бұрын
@@KitokebooLooking forward to it. Much appreciated
@chisoxnation9499
@chisoxnation9499 2 жыл бұрын
Is there a performance or structural benefit to using Main instead of setting up the host in a constructor or Startup method?
@Kitokeboo
@Kitokeboo 2 жыл бұрын
Great question. It is largely structural, not really a performance reason. In the code that I showed I simply instantiated the App class calling its default constructor. However, I could have created it by resolving it from the DI container just like the I did for MainWindow. This would allow the App class to have a non-default constructor that also accepts dependencies from the DI container.
@chisoxnation9499
@chisoxnation9499 2 жыл бұрын
@@Kitokeboo Thanks for the reply. I haven't worked with desktop apps in awhile and it kind of looks like a WinForms Program class but having to put the extra build options in the csproj.
@RayCarrot
@RayCarrot 2 жыл бұрын
This video is very helpful! I'm always interested in seeing these sort of examples of more real-world scenarios. I have a question about the dependency injection. Right now everything gets set up when the app launches. What if you had a service you would only want created first much later? For example in your app you have ThemeColor. You create a delegate for it since you need to pass in a normal parameter as well as the services, but what if the constructor only had services in it (which the DI could then automatically resolve)? Would you still use a delegate so that it can created at a later point or is there a better approach of being able to get new services after the constructor?
@Kitokeboo
@Kitokeboo 2 жыл бұрын
Great question. Most of the time when you register types with your DI container they will not be created until they are requested. For example the services.AddSingleton(); call registers the type MainWindow, but does not create an instance of it until it is requested. This deferred instantitation is a bit hidden, since one of the first things the app does when starting is request an instance of the MainWindow (but it is important to note it is not created until that point). In general, if you simply register a type, it will not be instantiated until it is requested. There is no need to use the factory pattern (what I ended up using a delegate for) simply to defer instantiation. If you have code that does need to instantiate a type from the DI container, I would still use a factory pattern for that. One thing I was not able to get to (likely will do it in the next stream), was the different types of objects. Often your classes can be broken into services and data classes. Services tend to perform work, often have other service dependencies, and are typically resolved from the DI containers. Data classes tend to be simpler C# objects, that hold data, have very few (if any service dependencies). It can be perfectly fine to instantiate data object in your code. The key is to understand that when you instantiate an object directly, you are causing tight coupling between the class calling the constructor and the class being instantiated. Whether this is good, bad, or indifferent will depend on your specific circumstances. What is important is to evaluate it.
@RayCarrot
@RayCarrot 2 жыл бұрын
@@Kitokeboo If I understand correctly then if I were to want to request a new service at a later point then the factory pattern is the best approach? For example say in the main window that I create and show a new window from an event handler. This window that I want to create is a service (a transient) which has a constructor which takes in some other services. How would I request it from inside the event handler? Using the factory approach, or is there a more direct way of getting it from the DI container (like a reference to the service provider)?
@Kitokeboo
@Kitokeboo 2 жыл бұрын
Yes, you understood correctly. A factory pattern would be the best approach there. Rather than taking in the factory as a dependency, you can add a dependency to IServiceProvider and use that to resolve items. In many cases I discourage direct usage of IServiceProvider because it is rare that your code actually needs access to everything in the DI container (you can think of it like a factory for all types). For the case of showing additional windows or dialogs, I often will put an abstraction layer between my event handler and showing the window. I am planning on trying to show some examples of this on my next stream.
@maometus
@maometus 7 ай бұрын
The package Microsoft.Extensions.DependencyInjection already included in the package Microsoft.Extensions.Hosting there is no need to reinstall it again after installing the hosting package.
@Kitokeboo
@Kitokeboo 7 ай бұрын
Ah good catch, and yes you are correct. The only time you need to directly reference a dependent library is when you need to explicitly control its version.
@HotSaab
@HotSaab Ай бұрын
Background music was way too loud.
@Kitokeboo
@Kitokeboo 16 күн бұрын
Thanks, I have gotten this feedback before and have removed it on my newer videos.
@wellington18m
@wellington18m Жыл бұрын
Hello there, Thanks a lot your your videos. They are leally helpfull. I have a question. What is the difference of implementing the generic host to implement DI and having something like this public App() { this.InitializeComponent(); ServiceCollection services = new(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); } private void ConfigureServices(ServiceCollection services) { services.AddTransient(); services.AddTransient(); services.AddScoped(); } I asked because Im fearly new in programming. Thnaks in advance!!
C#/WPF - TextBoxes, Hints, and Templates oh my
1:58:00
Kevin Bost
Рет қаралды 454
C# - System.CommandLine with Benjamin
2:44:24
Kevin Bost
Рет қаралды 258
Mama vs Son vs Daddy 😭🤣
00:13
DADDYSON SHOW
Рет қаралды 50 МЛН
Secret Experiment Toothpaste Pt.4 😱 #shorts
00:35
Mr DegrEE
Рет қаралды 38 МЛН
لااا! هذه البرتقالة مزعجة جدًا #قصير
00:15
One More Arabic
Рет қаралды 14 МЛН
Structuring Dependency Injection In ASP.NET Core The Right Way
16:22
Milan Jovanović
Рет қаралды 51 М.
What's new in C# 10
29:28
dotnet
Рет қаралды 87 М.
Switching Between Multiple Views in MVVM - EASY WPF (.NET CORE)
12:29
C#/WPF - Learning the DataGrid
1:42:38
Kevin Bost
Рет қаралды 10 М.
C#/WPF - Control Templates and Numeric Up/Down control
2:10:45
Switching Views - WPF MVVM NAVIGATION TUTORIAL #1
15:28
SingletonSean
Рет қаралды 100 М.
Creating a Download Progress Bar in .NET MAUI
5:04
HowToCode
Рет қаралды 73
Xiaomi SU-7 Max 2024 - Самый быстрый мобильник
32:11
Клубный сервис
Рет қаралды 551 М.
Vision Pro наконец-то доработали! Но не Apple!
0:40
ÉЖИ АКСЁНОВ
Рет қаралды 453 М.