.NET MAUI – Forget Me Not – Part 6

Building on the previous postings, today I want to discuss the magic of Dependency Injection (DI)

Dependency Injection makes for cleaner and more testable code. We’ll get into testing and Mocks in a later blog post, but using DI allows you to substitute a mock service for a real one. In any case, it is magical.

Even though this is powerful, this posting will be short, because once you know how to do it, it is very easy.

Let’s look at BuddyPreferences. This is the page that lists all the preferences of a specific buddy. We start, in BuddyPreferences.xaml.cs by creating BuddyPreferencesViewModel so that it can be our BindingContext. We pass the ViewModel into the constructor. Here is the complete class:

public partial class BuddyPreferences : ContentPage
{
    private BuddyPreferencesViewModel vm;
    public BuddyPreferences(BuddyPreferencesViewModel vm)
    {
       this.vm = vm;
       BindingContext = vm;
       InitializeComponent();
    }

}

As you can see, the BuddyPreferenceViewModel is passed in. But where does it come from? Who passes it in? That is the magic of an InversionOfControl (IOC) container, which .NET MAUI provides to you for free. All you need do is register all your pages, viewmodels and services in MauiProgram.cs:

var builder = MauiApp.CreateBuilder();
builder
    .UseTelerik()
	.UseMauiApp<App>()
    .UseMauiCommunityToolkit()
    .ConfigureFonts(fonts =>
	{
		fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
		fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	});


// Pages
 builder.Services.AddTransient<About>();
 builder.Services.AddTransient<BuddyDetail>();
 builder.Services.AddTransient<BuddyList>();
 builder.Services.AddTransient<View.Preferences>();

// Services
builder.Services.AddSingleton<BuddyService>();
builder.Services.AddTransient <PreferencesService>();

// ViewModel
builder.Services.AddTransient<BuddyListViewModel>();
builder.Services.AddTransient<BuddyDetailViewModel>();
builder.Services.AddTransient<BuddyPreferencesViewModel>();

return builder.Build();

As you can see in this excerpt of Mauiprogram.cs, we’ve registered the BuddyPreferences page, and the viewModel (Note, the reason we write View.Preferences is to avoid a name collision).

With that in place, the BuddyPreferencesViewModel is supplied by .NET MAUI to the constructor of BuddyPreferences, as shown above. You do not ever new-up a BuddyPreferencesViewModel – the creation of the VM is taken care of for you.

Notice that BuddyPreferencesViewModel is marked with AddTransient. There are two ways to add a page/service/view to the IoC – Transient and Singleton. If you make something a singleton as we do with the BuddyService then each time you get the service you get the same one. If you mark it transient, then each time you get it, you get a new one. General guidence is to use Singleton if you’ll be getting that object a lot (save memory) or if you need to preserve state.

The ViewModel itself depends on having an instance of BuddyService. We give it to BuddyPreferencesViewModel in the same way, by injecting it into the constructor

 private readonly BuddyService buddyService;

 public BuddyPreferencesViewModel(BuddyService buddyService)
 {
     ShowActivityIndicator = true;
     this.buddyService = buddyService;
 }

Go back and look at the creation of the BuddyPreferencesViewModel. No where is a new BuddyService “newed-up” and passed in. The Buddy Service is there because you registered it and so MAUI knows where to find it and what it depnds on. MAUI will not only create the BuddyService, but also any other classes in the chain of dependencies.

You’ll see this pattern throughout ForgetMeNot, and any well designed MaUI program.

Note: This pattern and Inversion of Control containers have been around for a long time. What is very nice here is that it is all built into MAUI.

Unknown's avatar

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. Liberty is a Senior AI Engineer at the University of Pittsburgh Medical Center, and was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 21 year Microsoft MVP.
This entry was posted in Essentials and tagged , , . Bookmark the permalink.

204 Responses to .NET MAUI – Forget Me Not – Part 6

  1. JosephDuh's avatar JosephDuh says:

    mjuk bettskena apotek beställ glasögon online apotek finland leverans sverige

  2. Edwinveite's avatar Edwinveite says:

    https://pharmrate.monster/# my mexican pharmacy

  3. JosephDuh's avatar JosephDuh says:

    Viagra pas cher livraison rapide france Viagra 100 mg sans ordonnance Viagra homme prix en pharmacie sans ordonnance

  4. 注册's avatar 注册 says:

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  5. Richardkig's avatar Richardkig says:

    Meilleur Viagra sans ordonnance 24h: Viagra sans ordonnance 24h suisse – Viagra homme prix en pharmacie

  6. Jamesmug's avatar Jamesmug says:

    Buy Tadalafil 20mg Buy Tadalafil 5mg Tadalafil Tablet

  7. JamesEsoli's avatar JamesEsoli says:

    Dr. Macksood Urologist ed pills for sale

  8. Craigpes's avatar Craigpes says:

    https://www.altipure.fr/# Viagra prix pharmacie paris

  9. PatrickBep's avatar PatrickBep says:

    Viagra Pfizer sans ordonnance Sildenafil teva 100 mg sans ordonnance Viagra homme prix en pharmacie sans ordonnance

  10. GregoryVar's avatar GregoryVar says:

    Buy Cialis online: buy cialis pill – LifeFlow Pharmacy

  11. Louistrugs's avatar Louistrugs says:

    Whoa a good deal of useful advice.
    Wein Plaza – https://weinplaza.com/

  12. DavidBus's avatar DavidBus says:

    https://precisioncarepharm.shop/# Buy Vardenafil 20mg online

  13. OctavioAmoub's avatar OctavioAmoub says:

    MexiCare Direct: MexiCare Direct – MexiCare Direct

  14. Jamesacutt's avatar Jamesacutt says:

    https://mexicaredirect.shop/# mexican online mail order pharmacy

  15. OctavioAmoub's avatar OctavioAmoub says:

    precription drugs from canada: ordering drugs from canada – Easy North RX

  16. Jerrywex's avatar Jerrywex says:

    Easy North RX legit canadian online pharmacy canadian pharmacies shipping to usa

  17. OctavioAmoub's avatar OctavioAmoub says:

    MexiCare Direct: medicine from mexico – phentermine in mexico pharmacy

  18. I enjoyed your post. Thank you. I truly appreciate this post. Good job on this article! It’s like you wrote the book on it or something. A lot of people are into rip off. It’s like you read my thoughts! You are obviously very knowledgeable. It’s like you read my thoughts! I have been looking everywhere for this! I enjoyed reading what you had to say. I truly appreciate this post. It’s like you read my thoughts! Nice read. I really like your article. Your article has proven useful to me. It’s like you read my thoughts! You’ve made my day! Thx again.

  19. JamesSog's avatar JamesSog says:

    canadian pharmacy victoza: best canadian online pharmacy reviews – Easy North RX

  20. IsmaelNiz's avatar IsmaelNiz says:

    I like how this post keeps the ideas well explained and accessible while also maintaining a balanced and natural conversational style throughout.

    fastest withdrawal online casino canada

  21. Jamesacutt's avatar Jamesacutt says:

    http://fleximedsindia.com/# indian pharmacies safe

  22. ShanepiliA's avatar ShanepiliA says:

    The discussion here feels very well paced and approachable, because the ideas are introduced in a simple way and the overall tone remains calm, pleasant, and open for readers who want to participate in the conversation.

    casino en ligne retrait immediat

  23. LhanepiliA's avatar LhanepiliA says:

    I appreciate how this post stays well-considered and informative while still feeling accessible and natural, because that combination usually makes discussions more enjoyable and encourages people to interact in a positive way.

    casino en ligne retrait instantane

  24. Randynek's avatar Randynek says:

    https://fleximedsindia.shop/# Online medicine order

  25. Apply now's avatar Apply now says:

    Great post! Nice read. I really like all the points you have made. Thumbs up!

  26. HiramLuh's avatar HiramLuh says:

    amoxicillin generic amoxicillin for sale amoxicillin buy no prescription

  27. This is an excellent, an eye-opener for sure! I truly appreciate this post. This information is magnificent. Good job on this article!

  28. ShanepiliA's avatar ShanepiliA says:

    I have read quite a few different takes on this general subject recently, but your article stands out because of how methodically you present the facts while still keeping the tone very straightforward and straightforward.

    https://gerardzwanenburg.nl/

  29. GichardAmomi's avatar GichardAmomi says:

    This post provides a really strong overview that covers all the necessary bases without any unnecessary opinion. I think anyone who stumbles upon this page will find a lot of value in your writing.

    купить inmode Body FX

  30. This design is spectacular! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  31. Rodneybox's avatar Rodneybox says:

    dosage for semaglutide semaglutide

  32. BrianTed's avatar BrianTed says:

    liraglutide https://usobesityscience.org/glp-1-agonists/ semaglutide withdrawal symptoms

  33. black penis's avatar black penis says:

    It’s like you wrote the book on it or something. Thumbs up! This is an excellent, an eye-opener for sure! I enjoyed reading this. The people at jail bait are con artists. This is an excellent, an eye-opener for sure! This is an excellent, an eye-opener for sure! This is some really useful information. Nice write up. I truly appreciate this post. Great post! You’ve made my day! Thx again. Thanks for writing this. Interesting content. Great read. I enjoyed your post. Thank you. Great post!

  34. BrianTed's avatar BrianTed says:

    Advancing Clinical Research in Metabolic Health and Weight Management https://usobesityscience.org/semaglutide-research/ is semaglutide safe for weight loss

  35. TimothySet's avatar TimothySet says:

    is zepbound semaglutide glp-1 agonists

  36. King Donkey's avatar King Donkey says:

    Good job on this article! But I often miss the old days. Nice read. I enjoyed your post. Thank you.

  37. Free Xanax's avatar Free Xanax says:

    Thanks for writing this. Would you suggest using these tips in a school setting? Interesting content. Thumbs up!

  38. snetsligt's avatar snetsligt says:

    Afhankelijk van waar je Sugar Rush speelt, is de gemiddelde Return To Player (RTP) 94,20%, 95,20% of 96,20%. Sugar Casino is een mierzoete goksite waar je geen tandarts zult zien spelen. Je kunt er spelen in het uitgebreide live casino of kiezen uit een meer beperkt casino aanbod. Gelukkig bieden ze een interessante welkomstbonus met cash spins. Let wel op de uitgesloten gokkasten. Depuis 1969, l’auto-école Belpeer est fière de vous accompagner tout au long du parcours de votre formation à la conduite, jusqu’à l’obtention de votre permis de conduire. Depuis 1969, l’auto-école Belpeer est fière de vous accompagner tout au long du parcours de votre formation à la conduite, jusqu’à l’obtention de votre permis de conduire. Spelers die wel van wat zoetigheid houden, kunnen hun hart ophalen bij de videoslot Sugar Bomb DoubleMax van game provider Jelly. Het speelveld in dit spel is gevuld met allerlei snoepjes. Niet alleen ziet dat er heel erg lekker uit, het kan door de speciale DoubleMax vermenigvuldiger ook nog leuke bedragen opleveren. Zowel het snoepjes-thema als de DoubleMax multiplier is niets nieuws in het online casino. Toch weet Jelly met Sugar Bomb DoubleMax een uniek spel neer te zetten.
    https://website.taxaccountantsinstitute.com/best-demo-session-mines-practice-before-you-play/
    Sugar rush casinobonus en beloningen Op de top van dat, hebt u dezelfde opties. Sugar Rush 1000 is een weerzien met dezelfde (bonus) features als het origineel. Ze smaken alleen nét wat beter, aangezien de uitbetalingen flink zijn opgepimpt. We lopen alle speciale features in dit deel van de Sugar Rush 1000 slot review even kort met je door: xoxo Wildhearts Sugar Rush – iPhone 14 Plus hoesje Sugar Rush Dice door Pragmatic Play Sugar Rush 1000 ziet er vrijwel exact hetzelfde uit als het originele Sugar Rush. We bevinden ons opnieuw in Candy Land, waar we op een speelveld van 49 symbolen – 7 rollen met elk 7 rijen – winnende clusters van snoep moeten maken. Onze online casino-expert Jaimy is aan de slag gegaan met Sugar Rush. In haar video laat ze zien hoe het kleurrijke spel werkt en neemt ze je stap voor stap mee door de functies en spelregels. Wil je weten wat je kunt verwachten van deze zoete en populaire slot? Bekijk dan snel de video van Jaimy en ontdek hoe je Sugar Rush speelt.

  39. JohnnieMut's avatar JohnnieMut says:

    liraglutide otc us obesity science

  40. TimothySet's avatar TimothySet says:

    п»їbuy liraglutide orlistat

  41. Timsothybioli's avatar Timsothybioli says:

    I like how this post remains useful and relaxed at the same time, making the discussion pleasant to read online.

    no deposit bonus

Comments are closed.