Singleton vs Transient - What's the Difference in .NET Dependency Injection?

Sdílet
Vložit
  • čas přidán 3. 06. 2024
  • Singleton... Transient... When should you use what when building client apps and web apps with .NET? Registering your dependencies correctly has import implications when it comes to lifecycle events and how you users will interact with your application. I break down what you need to know.
    Links:
    Documentation: docs.microsoft.com/dotnet/cor...
    .NET MAUI DI video: • Dependency Injection w...
    Sample Code: github.com/jamesmontemagno/De...
    Join this channel to get access to perks:
    / @jamesmontemagno
    👕 Buy some swag! - jamesmontemagno.myspreadshop....
    ☕️ Buy me a coffee - www.buymeacoffee.com/jamesmon...
    Follow:
    👨‍💻 GitHub: github.com/jamesmontemagno
    🦜 Twitter: / jamesmontemagno
    📄 Website: www.montemagno.com
    📰 Newsletter: newsletter.montemagno.com/
    Chapters:
    00:00 - Introduction
    00:30 - What is the dependency injection service?
    01:36 - What is a singleton dependency?
    02:20 - What is a transient dependency?
    03:00 - Demo app walkthrough
    04:20 - Singleton View, Singleton ViewModel
    04:50 - Transient View, Singleton ViewModel
    05:50 - Transient View, Transient ViewModel
    06:30 - Singleton View, Transient ViewModel
    07:50 - Wrap-up & thoughts
    Disclaimer: This channel, videos, and streams are created in my spare time and are a product of me... James Montemagno! They are NOT officially affiliated or endorsed by Microsoft (my employer) in any way. Opinions and views are my own.
    What is on my hat? It is the CLE clothing logo because I am from Cleveland! Checkout their awesome CLE merch: cleclothingco.myshopify.com/
    What is that art on my wall? It is an original piece from the French street artist Gregos of La Butte Montmartre: / bcez1onhiqx
    My Setup:
    📷 Canon M50 Mark II - amzn.to/3P8R7lp
    💡 Nanoleaf Elements Lights - amzn.to/3umwJVW
    🎙 Blue Spark Microphone - amzn.to/3qgtYkq
    🎙 Blue Pop Filter - amzn.to/3jEWM3r
    🤳 Rode Microphone Arm - amzn.to/2Z68AlE
    🎧 Sony MDR7306 Headphones - amzn.to/372jxta
    📲 Stream Deck - amzn.to/373Uk1n
    📹 Elgato Cam Link - amzn.to/3a9eGbh
    📷 GoPro Hero - amzn.to/374lm90
    🖱 MX Master 2S Mouse - amzn.to/3d7J2gj
    ⌨️ Tecware Phantom Keyboard - amzn.to/3aUP4y9
    #dependencyinjection #dotnet #dotnetmaui #aspnetcore
  • Věda a technologie

Komentáře • 53

  • @JamesMontemagno
    @JamesMontemagno  Před rokem +3

    Want to learn about Scoped dependencies? Checkout my followup! czcams.com/video/HMN26wQ8J54/video.html

  • @bkaankose
    @bkaankose Před rokem +12

    Simple explanation James, thank you!
    One thing to note here is that (since it may not be clear with View-ViewModel example), avoid injecting transient into singletons. Because the object you define as 'short living or stateless' is now living in an object you define as 'global'. Your transient will live inside this singleton for the whole application lifetime and it may create thread safety issues.

  • @jewersp
    @jewersp Před rokem +2

    Great video. Nothing new to me, but it's great to actually see the differences in this way, it helps and confirms existing practices.

  • @candidodmv
    @candidodmv Před rokem +1

    Congrats James as always is comming awesome content!

  • @kopilkaiser8991
    @kopilkaiser8991 Před rokem

    Shared, subscribed, and liked. You deserve it. All of it brother. Best wishes to you for your progression and may you excel to your very best.

  • @lindomagaye8729
    @lindomagaye8729 Před 10 měsíci +1

    Thanks for such a great explanation, James. Since I started following you I'm learning a lot!

  • @faranahmadk7401
    @faranahmadk7401 Před 5 měsíci +1

    Excellent. It cleared all the doubts. Thanks James.

  • @vickyfikriachri2311
    @vickyfikriachri2311 Před 3 měsíci

    Thank for the video James. Super helpful.

  • @sam14032
    @sam14032 Před rokem +2

    Thanks ! Very easy to understand and super interesting.

  • @MotherOfTony
    @MotherOfTony Před rokem +1

    very good explanation of dependency injection, thank you james!

  • @hwod44
    @hwod44 Před rokem +1

    Great explanation. You could talk about STATIC variables inside Transient injections too. Thx James

  • @4Asteria
    @4Asteria Před rokem

    Very clear to the point.
    Thank you very much for your effort

  • @Namco78
    @Namco78 Před rokem +1

    Very good explanation, thank you for clarifying this.
    Great example, astonishing app 🙂

  • @christianzaragoza7575

    Que gran maestro James, te felicito por la excelencia de tus tutoriales

  • @breula
    @breula Před rokem

    Awesome! In the last example where the page was defined as single and model as transient if cliqued on increase button certainly the number goes from 5 to 1. James should have done this.

  • @rikudouensof
    @rikudouensof Před rokem

    Will add this in next weeked side project.

  • @michael_azzer
    @michael_azzer Před rokem

    Amazing explanation 👌

  • @PierreBritoM
    @PierreBritoM Před rokem

    Amazing explanation!

  • @letsdoit7630
    @letsdoit7630 Před rokem +4

    Thanks for the explanation. I am used to c# windows application designs and familiar with binding the UI with a database like SQL or mySQL directly or via background code, but am struggling to understand the structure when it comes to MVVM and .net MAUI and linking to a hosted sql DB. I would appreciate if this is something you could give your opinion about. Thanks for the good content.

  • @amnshumansunil3371
    @amnshumansunil3371 Před rokem

    Hi James can you please make a video on unit testing

  • @DavidDanosTech
    @DavidDanosTech Před 9 měsíci +1

    Smooth. Nice!!!!

  • @yeica
    @yeica Před rokem +2

    Finally an example without GUIDs, thank you

  • @jamesleonmiller4504
    @jamesleonmiller4504 Před rokem

    Thanks for explanation, James. Nice video.
    I am curios, what is practical difference between Get() and Resolve() when using introduced in Xamarin Forms, DependencyService?

  • @codingdave
    @codingdave Před rokem +2

    Great video @james. When would you use scope in a WPF/MAUI application? Maybe when you open a file the application can work on?

    • @JamesMontemagno
      @JamesMontemagno  Před rokem +1

      Never, for web apps only docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scoped

  • @mattrobb3566
    @mattrobb3566 Před 11 měsíci

    Thanks James. Was Using Maui for Windows App. Was using Transient for a Page which used Events (Events were enabled on appearing and disabled on disappearing). But noticed that the previously used transient Pages remained in memory and their event triggers triggered events in the New Page, so after leaving and returning to this page 3 or 4 times I was receiving 3 or 4 events when I should have received one!! Indicating the transient pages are remaining in memory! By switching the ViewModel and the the Page to Singletons this issue disappeared as would be expected. What I didn't understand is when transient pages are no longer being used why are they retained in memory?

  • @mojoojoseph8145
    @mojoojoseph8145 Před rokem

    Very concise.😁

  • @aslanamca8225
    @aslanamca8225 Před rokem

    Hello, I want to ask something I'm curious about.
    I create an instance of another class in a service registered as a singleton, with its new keyword.
    There will be only one instance of the singleton service within the application, but it will create another class inside it each time it is called.
    For example, if it is called 100 times, it will create 100 class instances. The last sample can be used but what about the previous 99 samples? Does the garbage collector detect and clean them or is this a memory leak issue?
    It's not the lifetime of the service I'm wondering about, it's what will be the class instances created in the singleton service.

  • @michaelrogers6935
    @michaelrogers6935 Před rokem

    So when you register a class with a dependency injection service, and somewhere in the app an instance is being instantiated, does it automatically consult the service to see if there's an object? And does that apply to *any* object that's being created? And is the dependency injection service just storing the objects to be injected (the dependencies) or does it also store the objects that will be the recipients of the dependencies? So, if MainPage depends on a View Model, do you need to store both the Main Page and View Model, or just the View Model? [I feel like I am soooo close to understanding this 😀

  • @BJBEAR989
    @BJBEAR989 Před rokem

    Great explanation of singleton and transient. What would you recommend in order to handle Android screen rotations in Maui? When using Xamarin a screen rotation caused the activity to be recreated which effectively destroyed the data in the view. I suppose my real question is does Maui preserve the contents of the view when the screen is rotated?

    • @JamesMontemagno
      @JamesMontemagno  Před rokem

      It preserves the screen state automatically. Android does by default now

  • @bernhardtarmann1254
    @bernhardtarmann1254 Před rokem +1

    Thanks James!
    I really understand Singeltons and Transients but I’ve got problems with the third type. What’s the secret of the Scoped instances?

  • @sheilainglin863
    @sheilainglin863 Před rokem

    AWESOME 👌 🆒️ 🙌 👍👍👍😁

  • @oktjona
    @oktjona Před rokem

    can you do a video on how to connect netmaui app to sqlserver

  • @dfmf1982
    @dfmf1982 Před 11 měsíci

    Hi James do you have a course in Udemy?

  • @sfuentesojeda
    @sfuentesojeda Před 10 měsíci

    how do I get back to a previous page but when a button is clicked?

  • @amrosalah01
    @amrosalah01 Před rokem

    does Xamarin packages still work with Maui ? things like Macha for background tasks for example

    • @JamesMontemagno
      @JamesMontemagno  Před rokem +1

      Some may be backwards compatible and some may to be updated, it depends on the package. On nuget you can see if it targets net6 then you know it is updated

  • @AdamsTaiwan
    @AdamsTaiwan Před rokem

    Still to early in the day for me to get this.
    What I've been doing lately is creating ViewModels that function as services. I instance them using a script and keep the instance reference in a Dictionary. Every instance contains a GetView(string name) which can return any bound named view and a Process(string command) which allows me to script the object.

  • @gwisekor
    @gwisekor Před rokem

    6:40 어렵지만 중요한 내용. 난 그냥 new를 쓰고 싶다. ㅎㅎ

  • @HackelSchorsch
    @HackelSchorsch Před rokem +1

    Transient pages loaded from the shell do not behave transient. This is a bug which is already open for months.

  • @knockout4907
    @knockout4907 Před rokem

    Is Singleton per user or global for everyone?

    • @JamesMontemagno
      @JamesMontemagno  Před rokem +1

      Singleton will return the same instance when requested.

  • @sakabas28
    @sakabas28 Před 3 měsíci

    JamesMontemagno => GEMSMontemagno ♥

  • @FabioGomesCG
    @FabioGomesCG Před rokem

    And AddScooped ?

    • @JamesMontemagno
      @JamesMontemagno  Před rokem

      For web projects only really docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scoped

  • @kishant4565
    @kishant4565 Před rokem

    Need to create a pdf / printable page like receipt printing /barcode stickers printing using .Net Maui, please help.

    • @JasonPurkiss
      @JasonPurkiss Před rokem

      just fyi when I want to create pdf's in Xamarin I open a web page from the app and send the app data to the web page and then save as pdf, a lot simpler, let me know if you find a better and cheaper way :) as not the fastest and easiest solution :( I tried all the other solution's on the net but couldn't get on with any of them

  • @NK-xw4uu
    @NK-xw4uu Před rokem

    By "request" do you mean a http request or do you mean request for an object?