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

  Рет қаралды 19,362

James Montemagno

James Montemagno

Күн бұрын

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

Пікірлер: 53
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Want to learn about Scoped dependencies? Checkout my followup! kzbin.info/www/bejne/fn6xY2mthp19a5Y
@bkaankose
@bkaankose Жыл бұрын
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.
@vickyfikriachri2311
@vickyfikriachri2311 4 ай бұрын
Thank for the video James. Super helpful.
@jewersp
@jewersp Жыл бұрын
Great video. Nothing new to me, but it's great to actually see the differences in this way, it helps and confirms existing practices.
@faranahmadk7401
@faranahmadk7401 5 ай бұрын
Excellent. It cleared all the doubts. Thanks James.
@candidodmv
@candidodmv Жыл бұрын
Congrats James as always is comming awesome content!
@lindomagaye8729
@lindomagaye8729 10 ай бұрын
Thanks for such a great explanation, James. Since I started following you I'm learning a lot!
@kopilkaiser8991
@kopilkaiser8991 Жыл бұрын
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.
@MotherOfTony
@MotherOfTony Жыл бұрын
very good explanation of dependency injection, thank you james!
@rikudouensof
@rikudouensof Жыл бұрын
Will add this in next weeked side project.
@sam14032
@sam14032 Жыл бұрын
Thanks ! Very easy to understand and super interesting.
@yeica
@yeica Жыл бұрын
Finally an example without GUIDs, thank you
@4Asteria
@4Asteria Жыл бұрын
Very clear to the point. Thank you very much for your effort
@Namco78
@Namco78 Жыл бұрын
Very good explanation, thank you for clarifying this. Great example, astonishing app 🙂
@christianzaragoza7575
@christianzaragoza7575 Жыл бұрын
Que gran maestro James, te felicito por la excelencia de tus tutoriales
@hwod44
@hwod44 Жыл бұрын
Great explanation. You could talk about STATIC variables inside Transient injections too. Thx James
@DavidDanosTech
@DavidDanosTech 9 ай бұрын
Smooth. Nice!!!!
@JamesMontemagno
@JamesMontemagno 9 ай бұрын
Thanks!
@breula
@breula Жыл бұрын
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.
@PierreBritoM
@PierreBritoM Жыл бұрын
Amazing explanation!
@michael_azzer
@michael_azzer Жыл бұрын
Amazing explanation 👌
@mojoojoseph8145
@mojoojoseph8145 Жыл бұрын
Very concise.😁
@codingdave
@codingdave Жыл бұрын
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 Жыл бұрын
Never, for web apps only docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scoped
@letsdoit7630
@letsdoit7630 Жыл бұрын
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.
@jamesleonmiller4504
@jamesleonmiller4504 Жыл бұрын
Thanks for explanation, James. Nice video. I am curios, what is practical difference between Get() and Resolve() when using introduced in Xamarin Forms, DependencyService?
@amnshumansunil3371
@amnshumansunil3371 Жыл бұрын
Hi James can you please make a video on unit testing
@sheilainglin863
@sheilainglin863 Жыл бұрын
AWESOME 👌 🆒️ 🙌 👍👍👍😁
@mattrobb3566
@mattrobb3566 11 ай бұрын
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?
@BJBEAR989
@BJBEAR989 Жыл бұрын
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 Жыл бұрын
It preserves the screen state automatically. Android does by default now
@bernhardtarmann1254
@bernhardtarmann1254 Жыл бұрын
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?
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Gotta wait until next week to find out tehehehe
@oktjona
@oktjona Жыл бұрын
can you do a video on how to connect netmaui app to sqlserver
@michaelrogers6935
@michaelrogers6935 Жыл бұрын
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 😀
@sakabas28
@sakabas28 3 ай бұрын
JamesMontemagno => GEMSMontemagno ♥
@aslanamca8225
@aslanamca8225 Жыл бұрын
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.
@sfuentesojeda
@sfuentesojeda 11 ай бұрын
how do I get back to a previous page but when a button is clicked?
@dfmf1982
@dfmf1982 11 ай бұрын
Hi James do you have a course in Udemy?
@amrosalah01
@amrosalah01 Жыл бұрын
does Xamarin packages still work with Maui ? things like Macha for background tasks for example
@JamesMontemagno
@JamesMontemagno Жыл бұрын
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 Жыл бұрын
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.
@HackelSchorsch
@HackelSchorsch Жыл бұрын
Transient pages loaded from the shell do not behave transient. This is a bug which is already open for months.
@pablomontesmorquecho5388
@pablomontesmorquecho5388 7 ай бұрын
Have you find any workaround to this?
@gwisekor
@gwisekor Жыл бұрын
6:40 어렵지만 중요한 내용. 난 그냥 new를 쓰고 싶다. ㅎㅎ
@knockout4907
@knockout4907 Жыл бұрын
Is Singleton per user or global for everyone?
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Singleton will return the same instance when requested.
@FabioGomesCG
@FabioGomesCG Жыл бұрын
And AddScooped ?
@JamesMontemagno
@JamesMontemagno Жыл бұрын
For web projects only really docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scoped
@kishant4565
@kishant4565 Жыл бұрын
Need to create a pdf / printable page like receipt printing /barcode stickers printing using .Net Maui, please help.
@JasonPurkiss
@JasonPurkiss Жыл бұрын
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 Жыл бұрын
By "request" do you mean a http request or do you mean request for an object?
How Dependency Injection Works in #csharp
43:52
Raw Coding
Рет қаралды 52 М.
MVVMS... A Better MVVM? Model-View-ViewModel-Services Explained
14:23
James Montemagno
Рет қаралды 29 М.
Ну Лилит))) прода в онк: завидные котики
00:51
Who’s more flexible:💖 or 💚? @milanaroller
00:14
Diana Belitskay
Рет қаралды 19 МЛН
1🥺🎉 #thankyou
00:29
はじめしゃちょー(hajime)
Рет қаралды 79 МЛН
WHY and HOW to Add .NET Aspire to ANY .NET API and Web App in Minutes
22:02
.NET MAUI Explained: What is it, How does it work, and What about Blazor?
34:28
The .NET dependency injection methods you are not using
11:49
Nick Chapsas
Рет қаралды 91 М.
Working with Null in .NET 6 and C# 10
57:26
IAmTimCorey
Рет қаралды 35 М.
ASP.NET Core - Service Scope - Singleton vs Scoped vs Transient
10:11
Не обзор DJI Osmo Pocket 3 Creator Combo
1:00
superfirsthero
Рет қаралды 1,3 МЛН
Урна с айфонами!
0:30
По ту сторону Гугла
Рет қаралды 945 М.