.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. PeterceW's avatar PeterceW says:

    mexico pharmacy price list: mexican pharmacy what to buy – AccessBridge Pharmacy

  2. PeterceW's avatar PeterceW says:

    pharmacy websites: FormuLine Pharmacy – best mail order pharmacy

  3. livgyibge's avatar livgyibge says:

    The bet sizes available in Gates of Olympus start from 20p.   Greek mythology has long been a captivating theme in the world of online slots. In this segment, we’ll introduce you to a selection of Greek-themed slot games. The Gates Of Olympus slot machine, like all digital products from the Pragmatic Play developer, features simple controls with intuitive settings. Before you start spinning the reels, you need to set the bet size, decide how to start the spin – manually or automatically, and also look at the payout table. The latter will give an idea of the rules of the model, the cost of clusters and ways to unlock bonus modes. I found that the Gates of Olympus demo mode helped me to learn the features before I started playing for real money. Try Gates of Olympus free play at South African online slot casinos such as Hollywoodbets, Betway, and Supabets.
    https://m.eleotinspanish.com/?p=229193
    Match 8-30 symbols anywhere on the grid to win. Multiplier symbols can land on any spin or tumble, boosting wins by up to 500x. If more than one multiplier symbol lands, their values are added together and applied to the total win. Gates of Olympus distinguishes itself with an emphasis on its multiplier feature and its availability throughout the game. Random multipliers can appear on any spin, with values up to 500x, which can create massive payouts, particularly when several appear in tandem. Gates of Olympus also provides a free spins bonus, unlocked by landing four scatter symbols, with multipliers remaining active and accumulative throughout the feature. For players seeking an added challenge, the game also offers an option to buy the free spins for a cost, akin to Sweet Bonanza’s purchase option.

  4. MarvinCot's avatar MarvinCot says:

    AccessBridge AccessBridge AccessBridge

  5. gdzhmyjxk's avatar gdzhmyjxk says:

    Infernal cultists, sex dungeon deviants, inhuman abominations and Pinhead himself unite to create this nightmarish survival horror action experience Saber Interactive and Boss Team Games Develop, train, and deploy AI models. Starfield is the first new universe in over 25 years from Bethesda Game Studios, the award-winning creators of The Elder Scrolls V: Skyrim and Fallout 4. This next generation role-playing game marks a return to the studio’s deep RPG roots of meaningful customization, dialogue, and choice. Create any character you want and explore with unparalleled freedom as you embark on an epic journey to answer humanity’s greatest mystery. Starfield is the first new universe in over 25 years from Bethesda Game Studios, the award-winning creators of The Elder Scrolls V: Skyrim and Fallout 4. This next generation role-playing game marks a return to the studio’s deep RPG roots of meaningful customisation, dialogue and choice. Create any character you want and explore with unparalleled freedom as you embark on an epic journey to answer humanity’s greatest mystery.
    https://psoemoratalla.es/index.php/2026/04/16/fortune-clock-casino-login-a-review-for-uk-players/
    This app was great to use, but after all the updates that have been done, my kids can’t use any more 😢😢 you have to have IOS 15 or more in order to download any game; which I can’t do it now since I have iPad Air and it’s old now and I can’t update after IOS 12.5. I have 4 Osmo games and just got the Genius starter kit but all of them are useless now, unfortunately I can’t use anyone of them. You have to make apps that works for the people with old version of iPad. In keeping with the design we know and love, but stylised with a more modern edge, More Magic Apple presents the characters in a stunning, full-colour design against a magical forest backdrop. The ethereal soundtrack only adds to the fairytale vibe, taking you on an enchanting pokies adventure. We use your location to show you delivery options faster. We found your location using your IP address or because you entered it during a previous visit to Apple.

  6. Danielsuice's avatar Danielsuice says:

    пин ап пин ап казахстан

  7. Georgetasty's avatar Georgetasty says:

    pin up az online pin up az

  8. Justinmub's avatar Justinmub says:

    pharmacy discount coupons: CivicMeds – reliable canadian pharmacy

  9. DavidVoill's avatar DavidVoill says:

    http://civicmeds.com/# pharmacy website

  10. Justinmub's avatar Justinmub says:

    pharmacy prices: canada online pharmacy – online pharmacy india

  11. yjtdfvmtp's avatar yjtdfvmtp says:

    Win criteria: Any real money spin in the participating games may trigger a random cash prize. Gambling can be harmful if not controlled and may lead to addiction! Use our online tools and play responsibly. The slot has several features, including a bonus prize wheel and free spins. Here, you can receive between eight and 25 free spins. To trigger them you must first activate the prize wheel. Additionally, once the bonus spins end, you’ll either receive additional free spins or a multiplier, with the former being the best way to reach its 250,000 max win. Prizes: Expected weekly prize pool of £ 210,000 in total, an expected daily prize pool of £ 30,000 across six thousand and five hundred (6,500) prizes in the form of X bet multiplier, Free Spins Bonus and Instant Bonus. We have a range of live roulette games available for you to browse, including the popular variations: American, European and French roulette. We even have double ball roulette where, as the name suggests, two balls are dropped into the wheel each spin!
    https://blog.tgsisthegoodsteward.com/index.php/2026/03/24/444-casino-game-review-find-the-444-casino-best-link-for-uk-access/
    The lucky penny slot stands as a beacon of entertainment within the realm of online gambling. With its engaging themes, potential for large rewards, and user-friendly mechanics, it offers an experience that both thrills and captivates. Players who approach the game with thoughtful strategies can enhance their enjoyment while engaging in a whimsical journey through a world filled with opportunity. © 2025 Lucky Penny The lucky penny slot demo is packed with exciting features designed to keep players engaged: © AllSlotsOnline.Casino 2019-2025 Sorry, this product is unavailable. Please choose a different combination. You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

  12. JamesAlano's avatar JamesAlano says:

    http://civicmeds.com/# mexican pharmacy what to buy

  13. sxkfjmsjn's avatar sxkfjmsjn says:

    Avec votre compte approvisionné, dirigez-vous vers la section « Mini-jeux » ou « Jeux instantanés » de Betify. Vortex étant l’un des jeux phares de Turbo Games, il est généralement mis en avant sur la page d’accueil de cette section. Si ce n’est pas le cas, utilisez la fonction de recherche ou filtrez les jeux par fournisseur (Turbo Games) pour le trouver rapidement. La disponibilité de Vortex dépend principalement des licences détenues par Turbo Games et des réglementations locales sur les jeux d’argent. Le jeu est accessible dans la plupart des pays européens, au Canada et dans certaines juridictions asiatiques, mais reste indisponible dans les zones où les jeux d’argent en ligne sont strictement interdits. Les casinos crypto peuvent parfois offrir une alternative dans certaines régions restreintes.
    https://www.ascoms.com.au/decouvrez-le-vortex-de-turbo-games-depot-visa-facile-en-france/
    Le joueur peut également apprécier un environnement sonore de qualité. En effet, entre les parties, il peut profiter d’une mélodie épique jouée par des cordes, des percussions et des instruments à vent. Lorsqu’une combinaison payante fait irruption sur l’écran, des sons dynamiques retentissent et une animation impliquant les différents symboles gagnants est lancée. Robotnik est une machine à sous en ligne éditée par la société Yggdrasil Gaming. Ce jeu en trois dimensions transporte le joueur aux confins de l’espace. Lucky Haunter est une machine à sous de casino en ligne cool, ce tour de bonus commencera. La nouvelle modification de la Loi sur les jeux de hasard stipulait que des licences supplémentaires étaient nécessaires et que des moyens supplémentaires étaient nécessaires pour que les joueurs non seulement se protègent contre un problème de jeu, que vous pouvez faire tourner à tout moment.

  14. LamarBlick's avatar LamarBlick says:

    CoreBlue Health Viagra generic over the counter Viagra tablet online

  15. RayfordRhymn's avatar RayfordRhymn says:

    buy stromectol online usa: ivermectin oral tablets usa – parasite infection medication

  16. Keithdraiz's avatar Keithdraiz says:

    http://stericarepharmacy.com/# buy prednisone without a prescription best price

  17. Keithdraiz's avatar Keithdraiz says:

    http://amoxilfast.com/# where can i get amoxicillin 500 mg

  18. Keithdraiz's avatar Keithdraiz says:

    http://amoxilfast.com/# amoxicillin capsules online

  19. AllenLew's avatar AllenLew says:

    https://amoxilfast.com/# fast delivery amoxicillin usa

  20. Keithdraiz's avatar Keithdraiz says:

    https://ivermectinfast.shop/# antiparasitic medication usa

  21. RayfordRhymn's avatar RayfordRhymn says:

    ivermectin oral tablets usa: ivermectin fast – generic ivermectin online pharmacy

  22. RayfordRhymn's avatar RayfordRhymn says:

    amoxil without prescription usa: amoxil without prescription usa – amoxil without prescription usa

  23. Jameslen's avatar Jameslen says:

    https://certifiedmaplerx.com/# canadian pharmacy price checker

  24. JamesHEPLY's avatar JamesHEPLY says:

    https://bordervaluerx.shop/# mexican drugstore shipping to usa

  25. JeffreyRuize's avatar JeffreyRuize says:

    mail pharmacy: verified india drug manufacturers – canadian pharmacy price checker

  26. SteveAxott's avatar SteveAxott says:

    NorthCareRx NorthCareRx canadian king pharmacy

  27. Edwardcom's avatar Edwardcom says:

    https://bordercarerx.shop/# reputable pharmacies in mexico

  28. PhillipSem's avatar PhillipSem says:

    https://bordercarerx.com/# reputable pharmacies in mexico

  29. SteveAxott's avatar SteveAxott says:

    reputable canadian pharmacy canadian pharmacy NorthCareRx

  30. Richardroony's avatar Richardroony says:

    over the counter antibiotics pills OTC antibiotics otc uti medicine

  31. Ronaldtoife's avatar Ronaldtoife says:

    https://antimicrobialresearch.com/ Antibiotics Pharmacology

  32. Andreimiva's avatar Andreimiva says:

    Pharmacological Institute Pharmacological Institute viagra

  33. Andreimiva's avatar Andreimiva says:

    Pharmacological Sciences Research Institute Pharmacological Sciences Research Institute ed pills

  34. MichaelStago's avatar MichaelStago says:

    http://corevitalpharmacy.com/# Cialis without a doctor prescription

  35. Arthurnor's avatar Arthurnor says:

    generic sildenafil: Generic Viagra online – Generic Viagra online

  36. Arthurnor's avatar Arthurnor says:

    affordable ed medication: ed pills pharmacy – cheapest ed pills

Comments are closed.