Dependency Injection in WPF in .NET 6 Including the Factory Pattern

Поделиться
HTML-код
  • Опубликовано: 17 июл 2022
  • .NET Core has a built-in dependency injection that we use in every web project type we create. However, did you know that you can also use that same dependency injection in the .NET Core version of WPF? In this video, we are going to enable dependency injection in WPF and then use it for some common scenarios, including creating multiple forms.
    Full Training Courses: IAmTimCorey.com
    Source Code: leadmagnets.app/?Resource=DIi...
    Mailing List: signup.iamtimcorey.com/

Комментарии • 177

  • @m3xpl4y
    @m3xpl4y Год назад +17

    Dear Mr. Corey, I have to thank you a lot, for this exceptionally good explanation for DI in WPF. I just wanted to let you know, that all your free work here on YT is very much appreciated.

  • @rettogo9988
    @rettogo9988 Год назад +1

    I'm working on a WPF app right now, Tim, and this was a JIT video that gave me knowledge that is so handy for what I'm working on! Thank you so much!

  • @dougmcglothlin9624
    @dougmcglothlin9624 Год назад +5

    This was great. I have used dependency injection in WPF for a while, but still learned a lot. I got a much better understanding of what is happening; it is now something I own in my mind and not something that I can just copy and hope it works. Also, the Abstract Factory was new to me. I will definitely use it. Thanks.

  • @BeanCoffeeBean
    @BeanCoffeeBean Год назад +3

    Very important video ... most people know perfectly how to use DI in ASP.NET but have no idea how it is done in other projects

  • @waliqadri
    @waliqadri 9 месяцев назад

    Hi Tim, I really enjoyed this video! I appreciate the way you dive deep into topics and prioritize doing things the right way, even when shortcuts are available. For instance, your approach of creating an Interface for the library class stood out to me. I understand that for beginners, these finer points might seem puzzling, but once the underlying concept is clear, they'll surely be grateful for your thorough approach - just like me. Your expertise shines through your videos, often without you even realizing it. Even details like setting the form's width to 500 show your experience at play; you intuitively know that text won't fit well in anything smaller. Your videos are of exceptional quality, and I'm a devoted fan from Houston, TX. Keep up the fantastic work!

    • @IAmTimCorey
      @IAmTimCorey  9 месяцев назад

      I appreciate the kind words. I'm glad you find my content helpful.

  • @moonwaxing1
    @moonwaxing1 Год назад

    Perfect! was watching your older videos on Dependency Injection with a view to using it in WPF 👍

  • @0x00manu
    @0x00manu 3 месяца назад

    All your videos are true gems. Thanks for this tutorial!

  • @terrymackenzie6784
    @terrymackenzie6784 Год назад +7

    Tim, I had worked out 85% of this already but to show it with the abstract factory pattern is just brilliant, it is just amazes me why you give this stuff away for free. Now all I have to do is find a customer who wasn't to go to core before I rentier.

  • @abouttimebrewing3215
    @abouttimebrewing3215 Год назад

    Thank you Tim! I've been working in .NET 6 Web API and the dependency injection is SO easy it's effortless. This is a little different, but I get it now.

  • @ssushovan
    @ssushovan Год назад

    This is brilliant, Sir! Got to learn DI in another way. Thank you! 👏

  • @bojanpavlovic5038
    @bojanpavlovic5038 Месяц назад

    Awesome, Thanks Tim! I had something similar in mind for my prod app but this simplifies things even more.

  • @nikolayivanov5636
    @nikolayivanov5636 8 месяцев назад

    Thank you for this very usefull video. I was searching for wpf dependency injection for long time.

  • @marna_li
    @marna_li Год назад +5

    This is useful also to us who have been dealing with DI for a long time.
    I'm not working on anything using WPF right now but showing how to wire up a custom Host is useful. I have not created any Abstract Factories myself, but it might be useful. Accessing IServiceProvider is not so pretty.

  • @rolandwatz7797
    @rolandwatz7797 Год назад

    Hey Tim! After reading about 99lbs of Books and watching about 1k years of youtube - Videos, now I finally understood it. Watching your videos is never wasting of timel Thanks a lot

  • @pavfrang
    @pavfrang Год назад +3

    Your video is perfect!! I do a similar thing for Winforms using DI with NET 6.0.
    For the extension method I would return an IServiceCollection to allow the chaining of Add* commands.

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thank you! And that is a good option.

  • @freddyflares2757
    @freddyflares2757 Год назад

    Thank you, this was very helpful.

  • @isen1
    @isen1 Год назад

    very helpfull and interesting. as allways... thank you

  • @haroldemmers3678
    @haroldemmers3678 Год назад +2

    This is super stuff.
    My suggestion/request --> Add MVVM
    Or as how James Montemagno would call it --> MVVMS (Model View ViewModel Services) --> Give credit where credit is due ;)
    I would call it MVVML (Model View ViewModel Logic), because with dependency injection you can put pretty much anything in there, as you just proved.
    By the way, James used Maui to show this, which has the dependency injection already present in the template.
    Again, as always, great stuff Tim

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @stargarnet9139
    @stargarnet9139 Год назад

    He went SugestionPattern at the end. Great video!

  • @ABMedia83
    @ABMedia83 Год назад +1

    Thanks, this was very helpful

  • @NekoNihongo
    @NekoNihongo Год назад

    its very useful,i need learn the video more times。Dependency Injection always needed

  • @FrankBMorganKidder
    @FrankBMorganKidder 8 месяцев назад

    Very useful - thank you.

  • @reyaadelkomy8046
    @reyaadelkomy8046 Год назад

    Great Video!

  • @djengineeer
    @djengineeer Год назад +3

    The abstract factory is great. I also setup my extension to auto-attach the viewmodel for the new window as well.
    example: services.AddWindowFactory();
    then I have 2 generic types on the factory extension method. When adding a singleton for the delegate, I instantiate the window and the viewmodel and set the window.datacontext = the viewmodel and return the window.

    • @cizma27
      @cizma27 7 месяцев назад

      How did you do it? I can't wrap my mind around it.

  • @ahmeddabas
    @ahmeddabas Год назад

    Great tutorial ... u r the best ❤️

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thank you!

    • @ahmeddabas
      @ahmeddabas Год назад

      @@IAmTimCorey I hope to make video explain the best architecture to make desktop app using (Di - Factory Pattern - UnitOfWork)

  • @justhateeverything49
    @justhateeverything49 Год назад +1

    You are the man!

  • @florianb.9367
    @florianb.9367 Год назад

    thank you, amazing vid! :)

  • @RESIDENTECH1
    @RESIDENTECH1 Год назад

    👍👍👍👍👏👏👏👏👏👏👏 finally the official arrival #awesome

  • @paulegan3783
    @paulegan3783 Год назад +6

    Thank you Tim that's very helpful! Any chance you could build on this example adding CommunityToolkit.MVVM and databinding to view models (with both MainWindow and child forms)?

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @upcsatx
    @upcsatx Год назад +1

    Great Video!
    Question: If I inject the view into the viewmodel abstractly (as IMyView) does it still violate the MVVM rule about the ViewModel not having any knowledge about the view?

  • @amis6435
    @amis6435 Год назад +3

    CTRL + R + G => Removes unnecessary usings :) Not sure if you are aware of this hotkey, just sharing it with you in case you're not. Nice vid, thanks for sharing!

  • @zevspitz8925
    @zevspitz8925 9 месяцев назад

    Great video. Between this and your ASP .NET Core DI video, I'm finally starting to wrap my head around .NET dependency injection.
    8:02 Is there any reason not to configure and build the AppHost in the static constructor? Or even directly assign to the property?
    Or perhaps use a readonly static field?

  • @gonetolunch
    @gonetolunch Год назад

    Hi Tim, great video as always. I note that for the windows (like MainWindow) you add the implementation directly to DI, elsewhere I have seen code that has an interface to the view and then registers e.g. IMainWindow, MainWindow - like registering other dependencies. I don't see the point of creating an interface to the window, much like you show here. Is there any reason to? Similarly if using view models, would you create an interface to the view model? I can potentially see more use in that, but as view models are pretty tightly coupled to the view anyway and typically that's the main / only place to inject them, is it worth it?

  • @amanrohilla9278
    @amanrohilla9278 Год назад

    Great video

  • @schh486
    @schh486 Год назад +2

    Hi Tim! Thanks for your amazing content. Something ive been struggling with in WPF is getting environmentspecific appettingsfiles to work. That is a .Development.json, MACHINENAME.json etc. A little video on this would be great. Thabk you

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @mumk
    @mumk 7 месяцев назад

    Thanks, I'm able to use Autofac for DI now

  • @David-rz4vc
    @David-rz4vc Год назад

    Hey thanks! I was using this wacky way of doing DI before I saw this. Basically I was instantiating a new ServiceCollection within the main window Cs file and then adding it to the Resources after building the service provider (serviceCollection . Build service provider).
    The downside with this approach was I couldn't get EF Core migration to work (was complaining about extension hosting missing). So everytime I had to switch over to the Blazor project add my migration then set the WPF app as startup again. But it all make sense now; I needed that nuget package. But I do like the way u add it to app; alot easier.

  • @niangel2704
    @niangel2704 4 месяца назад

    Tim Corey, once again you amazed us!! Congratulations for your excellent tutorials!! Thanks a million!!
    I have a question though that could help a lot of us. My question is: how could we work around the DI part when our app is using community mvvm toolkit. For you this is a piece of cake to add 2-3 minutes to extend your video teaching us how to handle views and viewmodels and how to inject them and where. Thanks again for your excellent tutorials!!

    • @IAmTimCorey
      @IAmTimCorey  4 месяца назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @kiarashkanani8021
    @kiarashkanani8021 Год назад

    Another awesome video. thanks, Tim.
    but I have a question. Is it relevant to use Dotnet dependency injection with Caliburn micro instead of Caliburn micro's dependency injection?

  • @statslance3730
    @statslance3730 Год назад +1

    Hi tim, thanks for another great video. I wanted to ask i have been using IServiceProvider, ServiceCollection and BuildServiceProvider Method till now for DI in wpf. Should i switch to using IHost now? what would be the difference.

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      IHost adds more than just DI. It adds logging, configuration, and more.

  • @mwardell18290
    @mwardell18290 11 месяцев назад

    I love this video! I also am loving my Pay For Blazor Class! I am currently taking this in to the real world with the next challenge this video does not address. Unit Testing with NSubstitute/Moq the Abstract Factory Pattern. - It is more difficult that just Substituting for the Abstract Factory Pattern. We also need to Mock the Other Dependencies TForm and the Func. I only got as far as Mocking the Abstract Factory Pattern. Not sure how to Mock the others....Another video? Some custom consulting? Do you do Custom Consulting?

  • @user-zh3gd6kj6v
    @user-zh3gd6kj6v 9 месяцев назад

    Hi Tim, Tanks.
    What is best technology for develop commercial desktop app in 2023?
    Is MAUI useable for commercial purpose ?

  • @soundra7134
    @soundra7134 Год назад

    Thank you

  • @nguyenhoan3218
    @nguyenhoan3218 Год назад +4

    Hi Tim! The content is really great, but i have a question. Why the AppHost property at 7:43 is a static property and not a non-static property?

    • @esmail9189
      @esmail9189 Год назад

      up

    • @IAmTimCorey
      @IAmTimCorey  Год назад +5

      Because then the entire application can access the container without needing to instantiate it.

    • @CRBarchager
      @CRBarchager Год назад

      With static means it's available from the start of the program. You can think of it as a global variable (since it's public) available from anywhere while the program executes.

  • @omidmehdizadehard
    @omidmehdizadehard 6 месяцев назад

    very tanks

  • @BentRasmussen
    @BentRasmussen 5 месяцев назад

    Intetesting topic! Could you have injected the service provider and just asked that for a new instance in the click event handler?
    Also, managing resources with DI in scoped and keyed services in WPF is interesting. For example in F# it doesn’t seem possible to use specific window classes but using keyed services we can still discriminate between different windows (when specified in XAML).

  • @avidity2002
    @avidity2002 Год назад

    Very useful video Tim. I am new to WPF and .Net and I am dealing with something like this. But I am stuck because I am passing the environment variable and want to call the WCF service binding uri for that passed environment variable. Is this achievable using this? It looks to me like I have to first add the service binding for all the environment before I can call it? Or am I doing something totally wrong? It looks redundant to me to add the same service just to get it working for all environments. For Example if I pass the environment variable user input as Dev1 then I want the to do something by calling the Dev 1 service to be called. If I pass dev2 then dev2 Uri to be called. QA then qa uri and so on.. Basically developing an exe application in WPF with .Net framework and they want me to pass the environment variable. Please advise. Thanks

  • @parko1965
    @parko1965 Год назад

    hmm... does this also apply to WinUi3 apps? They don't have an OnExit() method. Any thoughts Tim?

  • @robertroxxor
    @robertroxxor Год назад

    very nice video, very helpful. would you do a basic tutorial on di in a blazor-hybrid-wpf project? in the microsoft docs tutorial they use services = new ServiceCollection() and Resources.Add("Services", services.BuildServiceProvider()); i followed your code sample to understand the differences, but it seems to me that the one created in app.xml has no relation to the "ServiceCollection" as created by MS example. i'm confused and would love to see a video explaining this. cheers

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @leelandclay4486
    @leelandclay4486 Год назад +1

    Hi. I have a question about the IHost object. You make it nullable, but then you use the ! to override the compiler warning. You stated when you created it, that it needs to be nullable. Can you explain why?

    • @marna_li
      @marna_li Год назад +1

      Allow me to answer. It is nullable to avoid the warning.
      Nullable reference types check whether fields and properties are assigned in the constructor when the members are not marked as nullable.
      Tim chose to init the host in the lifecycle event so to avoid the not initialized warning he used the bang (!) symbol when accessing the nullable Host property.
      You could new up the Host in the constructor of App class and assign the property there. Then you would not have to make it nullable. But putting logic in constructors are not advisable.
      I’m not sure why Host is static. Though.
      By default, the templates are not set up aa enforcing nullable reference type checks as errors. So all you get now are warnings.

    • @LeMustache
      @LeMustache Год назад +1

      @@marna_li It's just moving the warning from one, focused place to every usage of the property which essentially cannot or should not logically be null. The usage of NRTs is incredibly silly at times in this video.

    • @zevspitz8925
      @zevspitz8925 9 месяцев назад

      @@marna_li Host is static so as to be accessible from the entire application, e.g. to access GetRequiredServices.
      As for new-ing up the host in the constructor, that's precisely what Tim is doing.
      Unless you mean new-ing up in the static constructor?

  • @saminajjar5767
    @saminajjar5767 Год назад

    Thanks for the great video, this helped me create Console Apps with DI, but what is the difference between Apphost.RunAsync() and StartAsync(), seems like the task from RunAsync is not returning !

  • @ahmadkelany
    @ahmadkelany Год назад

    As always, thanks for the great content,
    Usually in a main window, the need arises to call many child forms, for example: a form for sale another for financial transactions, another for some reports...etc
    this could mount to tens of child forms for a complex business application,
    adding a parameter for each type of child forms in the main window constructor feels very wrong,
    is there another way to help in that scenario?

    • @turn1210
      @turn1210 Год назад +1

      I’ve seen it done with an collection of generic viewmodels in an AppViewmodel type container. When a new form is required, the viewmodel for that form is created and added to the list, the UI then opens a generic form and using templates, displays the correct layout for that viewmodel. It’s not going to save code over what Tim has done, but it encapsulates the form logic into the viewmodel that owns the form.

    • @ahmadkelany
      @ahmadkelany Год назад

      @@turn1210
      Thanks for your insightful comment
      I really appreciate it.

    • @turn1210
      @turn1210 Год назад +1

      @@ahmadkelany you’re welcome my friend 😊

  • @BraentR
    @BraentR Год назад

    Спасибо

  • @huazhang1506
    @huazhang1506 7 месяцев назад

    I want to capture video in WPF, using .net 6.0, but no resources/sample, could you help me

  • @cizma27
    @cizma27 7 месяцев назад

    How could I add existing ViewModel to a FormFactory as opposed to the View creating its own ViewModel?

  • @fifty6737
    @fifty6737 Год назад

    Microsoft Genric Host, Depenedancy Injection, Configuration, Logging ..etc is the best thing to happen to .NET, it just blows any other language out of the park in this

  • @micro2743
    @micro2743 Год назад +1

    Great Cideo, As Always! I would love to see a video on using this in a WinUI 3 Desktop App. I was able to launch MainWindow as a service using OnLaunched instead of OnStartup and Activate instead of Show. Microsoft loves renaming everything for no reason. Unfortinatly, I was not able to find a Windows SDK App equivilent for OnExit :(

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @diligencehumility6971
    @diligencehumility6971 Год назад

    So the factory is for when you want a new instance every time you ask for it. (I thought 'Transient' already did that).
    But most of the time you would want the same instance, if you are keeping track of state, navigation manager, etc.
    Or am I wrong?

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      A factory can accomplish different tasks based upon its design. For instance, the HttpClientFactory will handle the lifetime of HttpClients internally so that they are properly recycled and reused in order to not exhaust the sockets on a computer. Another factory might create a new instance when requested, which is different than creating a new instance when the class is constructed.

  • @bradleyr4451
    @bradleyr4451 Месяц назад

    hi Tim great video. Got to the end and you said its NOT! for .net framework, but for Core? Im doing .net framework because this app will hopefully be able to use older code? I want a Main form and then Child forms where its only 1 allowed (singleton) if possible. Will this example work in .net framework? Also
    I have never used the Factorial arg in c# before variable name becomes VARIABLE_NAME!!! thats so interesting. Im a dinosaur from punched cards and functional programming

    • @IAmTimCorey
      @IAmTimCorey  Месяц назад +1

      Yes, I was trying to be clear that I was using .NET Core (now just .NET) in the demo rather than .NET Framework. Things will be different in .NET Framework. You would need to use a third-party dependency injection library like Autofac, since DI is not built into .NET Framework.

    • @bradleyr4451
      @bradleyr4451 Месяц назад

      @@IAmTimCorey you said that its core not .net framework. I needed to switch to classic old winforms that i used for years and can get things done, here with wpf it seems so fragile and limited choice of items to put in the designer. I started with the microsoft DI and it failed at the spot of using ? or ! that in 7.1 isnt there, use version 8.0? you cant. Not sure if DI is needed the only idea was to bring in outside code of unknown type or version. I went from doing forms, to embedded cpp to web and now forgot things, I hope to have many panels depending on what its doing, a Tab control could work where each one is its own blank canvas? Trying to drop 5 panels on top of each other hoping to bring back the way its done? if there are 5 or 6 buttons on the left each opens its own majority of the page with its own buttons, text input etc, if wpf can do that better great.
      I did your example here maybe 5 times hoping to grasp it and its very well done and makes sense. repeating the task a few times helps to memorize it.

  • @jpsytaccount
    @jpsytaccount Год назад

    Is there anyway to do dependency injection through xaml? Like injecting view models with xaml?

    • @blackenedsprite8542
      @blackenedsprite8542 Год назад

      You can set the data context in xaml, but that will only give you an empty view model, it won't have anything populated. You can't put data into it through xaml.
      Reference your data context here
      That's the only way I know in xaml to get a VM going, everything else involves varying levels of C#

  • @CRBarchager
    @CRBarchager Год назад +1

    33:00 Eventhough this is just a sample app. It would be good to have some sort of counter or list of open windows so if you kill the MainWindow, the childforms will close as well so you don't need to close them seperately.

    • @Pete107
      @Pete107 Год назад

      Add each window/form into a collection when they're created.
      override OnClosing in MainWindow and iterate each window in the collection and call Close().

    • @LaurieC
      @LaurieC Год назад +1

      Easy. In your App.xaml add ShutdownMode="OnMainWindowClose". When you close the main window all child windows are automatically closed.

  • @goliat2606
    @goliat2606 Год назад

    What is the best way to pass parametr between 2 forms? For example object to edit?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      It depends on your situation, but remember that a form is just a class. You can pass in constructor parameters, you can subscribe to events, etc.

  • @S3Kglitches
    @S3Kglitches Год назад

    What if you need parameters for the factory.Create() function? I usually use parameters like fullscreen = true, size, center = true/false etc when creating windows using a helper function (and different parameters for different types of pre-defined utility windows -> e.g. a "form popup window (gets an UserControl as a parameter)" will be displayed without minimize/maximize box and a "fullscreen image displayer" (gets a byte[] or an Image as a parameter) will be displayed without borders and without title and buttoms)
    Is the solution creating a different IAbstractFactory for every of these types of windows? (one for no params, one for a "usercontrol form displayer", one for "image displayer") and thus getting 3 IAbstractFactory types with each one prescribing different params in the .Create() function?

    • @saminajjar5767
      @saminajjar5767 Год назад

      I don't know if this might help, but Dependency Injection works best with what is called Parameter objects, where you pass your parameters as Object and you define your classes as generics, this also helps you when have multiple implementations or decorators .

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      I showed how to do that in the previous video. I put the time marker at the time when we actually send parameters, so you can see how it can be done: ruclips.net/video/2PXAfSfvRKY/видео.html

    • @S3Kglitches
      @S3Kglitches Год назад

      @@IAmTimCorey Thank you very much.

  • @aziz12063
    @aziz12063 Год назад

    tks very much, Please if we have for example ChiledForm that accept a IDataAccess as a parameter, how can I open it from another form without using Factory, I don’t want to pass a IDataAccess as a parameter when I call ChildForm.Show();

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      You would get the child form from dependency injection. That way it gets the dependencies it needs too.

    • @aziz12063
      @aziz12063 Год назад

      @@IAmTimCorey the MainWindow is the parent form, i use Repository pattern, i pass the IRepo as a parameter, when i pass it to the constructor of MainWindow this gives me error:
      system.invalidoperationexception: 'unable to resolve service for type 'dataaccess.dbcontext' while attempting to activate 'dataaccess.repositories.genericrepository`1[repo.models.user]'.'
      then i create a variable for IRepo with new keyword and i pass it to childForm to open it, but if i do i must to pass a dbContext to create the IRepo variable:
      IGenericRepository repo = new GenericRepository(new DataAccess.DataContext());
      i don't want call or Pass DbContext in my frontend.
      tks

  • @TioPew
    @TioPew Год назад

    Hi Tim, do you have any course for non us people, I've seen on your site but after converting to us dollars it became too expensive. Can you make some cheaper modules?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      The paid content is used to fund the free content. That's why we keep it at the price we do. Lowering the price to accommodate more cultures and economies would actually reduce our capacity to make more free content. However, because of the pricing being where it is, we have been able to give away three full courses here on RUclips (TimCo Retail Manager, Tournament Tracker, and Suggestion App). We have over 11 days worth of videos here on the channel and more is being added every week.

  • @Dusthorn
    @Dusthorn Год назад

    How did you use assignment to dataAccessInfo not creating this form property?

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      The dataAccessInfo is the TextBlock on WPF form. That is what I named it. So, it has a bunch of properties for that TextBlock, including the Text property. That's the property we used to put text on the form.

  • @S3Kglitches
    @S3Kglitches Год назад +1

    Could you show the same for Windows Forms and how to use it with UserControls?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @TheMasterAbdul
    @TheMasterAbdul Год назад

    is there any play list for this tremendous subject and explaining?

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      I have a number of playlists on my channel that you can check out.

    • @TheMasterAbdul
      @TheMasterAbdul Год назад

      @IAmTimCorey
      Thanks alot, i wish to see more design patterns in wpf, especially modern .net 6+
      I want to use mediator pattern in wpf and have multiple threatds handling multiple things, so message passing between the components are done in the mediator

  • @mrt7948
    @mrt7948 Год назад

    if i use dotnet framework instead of dotnet6 will this example not work?

  • @semen083
    @semen083 Год назад

    Why use host for dependency injection, not just simple ServiceCollection?

    • @pavfrang
      @pavfrang Год назад

      Because it does a lot more. It adds services for Configuration and Logger stuff, which otherwise you would do manually. There is no need to do them manually, like in older days.

  • @programmer_rohan
    @programmer_rohan Год назад

    You can create a playlist named .net 6 and put all videos related to .net 6 in that. It would be easier to find.

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      A lot of the content that isn't marked as .NET 6 is still relevant for .NET 6. That would confuse people, which is why I haven't done it.

  • @numinaoneiron1655
    @numinaoneiron1655 Год назад

    Is it possible to do a video about Win UI 3 vs WPF.

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @djelasrca8091
    @djelasrca8091 2 месяца назад

    Microsoft.Extensions.DependencyInjection.Abstractions
    Can someone explain what is this package used for

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +1

      It gives us the keywords for accessing things more easily from Appsettings. It is an interfaces and abstractions library that other libraries build off of, so we can use it to get access to those same abstractions.

    • @djelasrca8091
      @djelasrca8091 2 месяца назад

      ​@@IAmTimCoreyI have another question if you can answer it. I have a list in WPF, and each item in the list has specific commands associated with it. When I click on a particular item, I want to change something on the view model. Each of my items depends on the view model, as well as on some other information. How can I correctly instantiate these items for my list? I cannot use a factory because it's not just the view model that I depend on; I also need to include additional information such as name, ID, quantity, etc.

  • @amanrohilla9278
    @amanrohilla9278 Год назад

    I have one question do you really see WPF now being used in the market?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Absolutely. The key is that a lot of desktop apps are really old (so they are still WinForms). For newer apps (made in the last 10-15 years), WPF has been a solid choice so a lot of companies have chosen it.

    • @amanrohilla9278
      @amanrohilla9278 Год назад +1

      @@IAmTimCorey I think companies are going with web apps now? Every desktop app is being made into web app.

    • @maltonic42
      @maltonic42 10 месяцев назад

      Would like to know that from Tim as well. I see a trend more towards webapps and away from desktop-apps...

  • @waynehawkins654
    @waynehawkins654 Год назад

    Totally lost on this one Tim. I not in the world of WPF so this is not helping.
    I have a Services Project that calls a Class Project method that then needs to call a EF Core using Repository and Interface.
    As a Blazor project, this all works out of the box with a simple @inject. Why so hard to get this to work in a Services Project.
    Do you have a video that shows close to this type of project setup. Services Project, calling a Class Project that calls Repository\Interface Project to do the EF things?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      It sounds like you just need to get dependency injection set up in your project. Then you just ask for what you need and get it. It should be no different than Blazor at that point.

    • @waynehawkins654
      @waynehawkins654 Год назад

      One would think Tim but it's seem not that easy. I trying Autofac to see I could in this.
      In a Blazor project I simple Add
      @inject IUsersRepository _userRepository
      And then I can call everthing.
      In a Services Project, no.
      Here what I have in the Services project but if I try to call a method in a IWhateEver, it a no go
      public static void Main(string[] args)
      {
      var builder = new ConfigurationBuilder()
      .AddJsonFile($"appsettings.json", true, true);
      BuildConfig(builder);
      var config = builder.Build();
      var dbWaterConsentsCoreConnection = config["ConnectionStrings:WaterConsentsCoreConnectionString"];
      IHost host = Host.CreateDefaultBuilder(args)
      .ConfigureServices(services =>
      {
      services.AddHostedService();
      services.AddDbContext(options => options.UseSqlServer(dbWaterConsentsCoreConnection));
      services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
      services.AddTransient();
      services.AddTransient();
      services.AddTransient();
      })
      .Build();
      //And my go at using Autofac.
      var builderAutofac = new ContainerBuilder();
      builderAutofac.RegisterModule();
      builderAutofac.RegisterModule();
      builderAutofac.RegisterType();
      builderAutofac.RegisterModule();
      builderAutofac.RegisterType()
      .As()
      .SingleInstance();
      builderAutofac.RegisterType()
      .WithParameter("options", DbContextOptionsFactory.Get(dbWaterConsentsCoreConnection))
      .InstancePerLifetimeScope();
      IOTDevicesRepository whyDontyouwork = new();
      whyDontyouwork.Get(1);
      var container = builderAutofac.Build();
      var studentRepository = container.Resolve();
      studentRepository.Print(oStudent);
      //This will not work.
      var iotRepository = container.Resolve();
      var pleasework = iotRepository.Get(1);
      host.Run();
      }

  • @burakhanbircan9850
    @burakhanbircan9850 7 месяцев назад

    How to use this with MVVM pattern.

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад

      There is no real change. You just get your ViewModels from dependency injection rather than instantiating them yourself.

  • @ivandrofly
    @ivandrofly Год назад

    4:00 How app starts
    6:00 Microsoft built-int injection package installation

  • @Dusthorn
    @Dusthorn Год назад

    I think everyone now is making only web applications

    • @IAmTimCorey
      @IAmTimCorey  Год назад +3

      No, the desktop app is still alive and well. They just aren’t used as much for sample projects. When you look at what businesses build (the people employing developers), there are still a ton that use desktop apps. They are the right choice in a lot of situations.

  • @Mobay18
    @Mobay18 Год назад

    Am I the only one who gets confused by the name Dependency Injection? I would have called it Global Reference or something.

    • @IAmTimCorey
      @IAmTimCorey  Год назад +1

      The reason it is called that (and this isn't C#-specific) is because we are injecting our resolved instances into classes when they state they have a dependency. So instead of a class having the line "var log = new Serilog()" in it somewhere, the class asks for a logger. The difference is that in the first way, the class forces the application to take on the Serilog dependency. In the second way, the class asks for some type of logger. It depends on a logger, but it doesn't care which one. Just one that satisfies the interface. So, when the application runs, the dependency injection system can figure out which logger to create and then it injects that instance into the class that requests it.

    • @Mobay18
      @Mobay18 Год назад

      @@IAmTimCorey Thanks for the explanation and the great content.

  • @JaredCollierFoster
    @JaredCollierFoster Год назад +1

    Hi Tim, I tried what you show but have encountered an issue. In my App.xaml, I have a Style defined in my ResourceDictionary with x:Key="GeneralButton". Over in my MainView.xaml, I bind to this style like so: Style="{StaticResource ResourceKey=GeneralButton}". However, in my MainView.xaml.cs, I run into an error when executing the InitializeComponent() line: "'System.Windows.Markup.XamlParseException... 'System.Windows.StaticResourceExtensions' threw an exceptioon... Exception: Cannot find resource named 'GeneralButton'. Resource names are case sensitive". My understanding is that before I was subscribed to the Application_Startup event: , which seems to have included an initialization of the ResourceDictionary in my App.xaml. When I override OnStartup, however, this seems to not take effect. I was wondering if you know how to keep my ResourceDictionary where it is, as well as overriding OnStartup. This approach seems more elegant to me than resubscribing to the Application_OnStartup event or putting my Style definition in MainView.xaml (I want it to be defined at the application level).
    Great video by the way - been learning a lot from you! I love dependency injection.

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      Sorry, I don't have a good example to show you and I'm not sure off of the top of my head. Maybe ask on Stack Overflow.

  • @LeMustache
    @LeMustache Год назад

    Hey, at 28:42 I miss the point of ignoring the warning instead of using GetRequiredService() instead. What's the reason behind that?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      I was in the head-space of thinking about nulls and focused on addressing that instead of remembering to require the service. 😆

    • @LeMustache
      @LeMustache Год назад

      @@IAmTimCorey Haha, I see.
      In my option you should overall limit the use of the bang operator to minimum.
      Don't know how experienced you are with Typescript but it's not uncommon to see it outright banned in some scenarios in many typescript projects. It's part of the reason why cases like this immediately pop a "warning" in my head as I see it more like a hack around pretty much an unsolvable problem of compiler not always knowing what logically is or is not possible, rather than something you should sprinkle around in your code.
      Just my 2 cents 🙂

  • @solomonmckay3126
    @solomonmckay3126 Год назад

    I tried creating something similar with my own DataAccess class, nothing special to it. I register it as a transient
    services.AddTransient();
    Later in a different class I try to get the service by calling AppHost.services.GetRequiredService();
    but this throws an error: "No service for DataAccess has been registered". Does anyone have an idea of what could be causing this issue?

    • @solomonmckay3126
      @solomonmckay3126 Год назад

      I forgot to mention that I created another data access class that uses the same IDataAccess interface. Could this be causing the issue?

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      You registered it as an IDataAccess but you are trying to access it using DataAccess. You need to access it using whatever you registered it as.

    • @solomonmckay3126
      @solomonmckay3126 Год назад

      @@IAmTimCorey I see. Thank you for the clarification.