Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MAUI dependency injection when to add Singleton/Transient

I realize this question is answered on Stack Overflow, but I'm looking for an "explain it like I'm a Golden Retriever" explanation, as a lot of the terminology (and some of the concepts) are unfamiliar to me.

In MauiProgram.cs, it's necessary to put in lines of code that look like this:

            builder.Services.AddTransient<SecondPageViewModel>();
            builder.Services.AddSingleton<IAlertService, AlertService>();

I have no idea when to use AddTransient or AddSingleton.

I understand the Singleton design pattern and I sort of understand dependency injection, but I don't understand how these lines of code deal with dependency injection, and, frankly, I don't understand the docs.

My suspicion is that when you navigate away from a page and it's Transient, the state of the Page / possibly some data associated with it are deleted, so when you navigate back to it, it's like the first time it's been shown.

But I could be wrong.

like image 372
Bob Avatar asked Oct 24 '25 16:10

Bob


1 Answers

Here is the life time definitions:

  • Singleton means that an object lives as long as the application lives.

  • Transient means that a new object is created every time you request a transient service.

  • Scoped means a limited lifetime, how long depends on the type of application. For a web service, it's usually from receiving an HTTP request to an HTTP response being sent. In an MAUI application, I don't know. Maybe for a page like you said?

Cleanup

There is also something else that the IoC container takes care of. And the is freeing up resources. That's done with the IDisposable interface. All Singleton and Scoped services will get cleaned up.

For transients, it's harder as the IoC container just acts like a factory for them (i.e. creating a new one every time without knowing how long they will be used).

like image 52
jgauffin Avatar answered Oct 26 '25 06:10

jgauffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!