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

    cheapest online ed treatment: PrimeLine Pharmacy – online ed drugs

  2. EdwardWaymn's avatar EdwardWaymn says:

    https://primelinepharmacy.shop/# where can i buy erectile dysfunction pills

  3. Anthonypam's avatar Anthonypam says:

    https://medbridgepharmacy.shop/# walmart pharmacy online

  4. super 9's avatar super 9 says:

    Super 9… Simple and effective branding! I haven’t played much myself, but a friend recommended it. Here’s their website so you can check for yourself super 9.

  5. If you want the esporte bet original experience, Sportingbe.net is where to go. Trust me, you won’t be disappointed. esporte bet original

  6. super 9 game's avatar super 9 game says:

    So, you are talking about the Super 9 game huh? Give it a playthrough, seems legit enough to sink some time into when you are bored super 9 game.

  7. PatrickZoolf's avatar PatrickZoolf says:

    mail order pharmacy: VitalCore Pharmacy – rx pharmacy coupons

  8. PatrickZoolf's avatar PatrickZoolf says:

    True Health Pharm: True Health Pharm – True Health Pharm

  9. Elmerrit's avatar Elmerrit says:

    https://happypawspharmacy.com/# dog and cat medicine supply

  10. PatrickZoolf's avatar PatrickZoolf says:

    pet pharmacy USA: pet pharmacy USA – pet antibiotics and care

  11. BennieWalse's avatar BennieWalse says:

    mostbet resmi: mostbet

  12. GregoryRox's avatar GregoryRox says:

    mostbet güncel adres: mostbet

  13. GregoryRox's avatar GregoryRox says:

    mostbet casino mostbet

  14. CurtisInses's avatar CurtisInses says:

    lisanslı casino siteleri: casino siteleri

  15. Your article helped me a lot, is there any more related content? Thanks!

  16. bethlehem pa casino

    References:
    md.swk-web.com

  17. Stephenviaps's avatar Stephenviaps says:

    Hi, this weekend is nice for me, because this point in time i am reading this great informative article here at my house.
    https://drive.google.com/file/d/1YS8cPuCuFEtnyeAhvB49YJhd2cLPaSPc/view?usp=sharing

  18. You absolutely crushed it with this one — WOW!

  19. Such a powerful and well-written post.

  20. EarnestCor's avatar EarnestCor says:

    Explore detailed insights on auto set dual alarm clocks at TOPCLOCKS, including features, comparisons, and expert recommendations for smarter buying decisions.

  21. Such an uplifting and electrifying read!

  22. ShanepiliA's avatar ShanepiliA says:

    Good day! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa? My blog discusses a lot of the same topics as yours and I think we could greatly benefit from each other. If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Great blog by the way!
    сайт leebet casino

  23. LewisGor's avatar LewisGor says:

    Hi there, yeah this article is really pleasant and I have learned lot of things from it regarding blogging. thanks.
    leebet casino

  24. Befolgen Sie einfach die Lösungen, und Sie werden im Handumdrehen wieder spielen können. Neue Spieler erhalten einen Willkommensbonus von bis zu 30 Euro
    in Freiwetten plus Casino-Bonus. 888casino bietet ein großartiges Spielerlebnis mit
    einer Vielzahl von Spielen, Werbeaktionen und einem ausgezeichneten Kundendienst.
    888casino bietet seinen Spielern mehrere Kontaktmöglichkeiten, um ein reibungsloses und angenehmes Spielerlebnis
    zu gewährleisten. Die Spielauswahl von 888casino bietet
    eine große Auswahl an Optionen für jeden Spielertyp.

    Von einsteigerfreundlichen Spielautomaten bis hin zu Blackjack-Tischen mit hohen Einsätzen hat 888casino alles zu bieten. Wenn Sie auf der Suche nach einem seriösen Online-Casino sind, das sowohl Spaß
    als auch Sicherheit bietet, dann ist 888casino eine gute Adresse für Sie.
    Die Plattform ist bekannt für ihre sichere Umgebung, ihr benutzerfreundliches Design und ihre vielfältige
    Auswahl an Spielen, darunter Slots, Tischspiele und Live-Casino-Optionen. 888casino ist eines
    der führenden Online-Casinos, das Spielern auf der ganzen Welt eine
    breite Palette an spannenden Spielen bietet. Es bietet eine breite Palette von spannenden Spielen, darunter Slots, Tischspiele und Live-Casino-Optionen. Glücksspiel kann süchtig
    machen, bitte spielen Sie verantwortungsbewusst.

    References:
    https://online-spielhallen.de/joo-casino-mobil-erleben-ihr-vollstandiger-leitfaden/

  25. Your mode of explaining everything in this piece of writing is genuinely pleasant, every one be capable of simply be aware of it, Thanks a lot.

  26. I like this website so much, bookmarked.

  27. Your article helped me a lot, is there any more related content? Thanks!

  28. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.info/en-IN/register?ref=UM6SMJM3

  29. binance's avatar binance says:

    Your article helped me a lot, is there any more related content? Thanks! https://www.binance.info/en-ZA/register?ref=JHQQKNKN

  30. 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?

  31. 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?

  32. xxx butt's avatar xxx butt says:

    Welcome for this useful information, I have bookmarked and written some things down. I will be checking back, from time to time too.

  33. xxx Model's avatar xxx Model says:

    Welcome for this useful information, I have bookmarked and written some things down. I will be checking back, from time to time too.

  34. Index Home's avatar Index Home says:

    Thank you, your article surprised me, there is such an excellent point of view. Thank you for sharing, I learned a lot.

  35. Your article helped me a lot, is there any more related content? Thanks! https://www.binance.com/register?ref=P9L9FQKY

  36. Your article helped me a lot, is there any more related content? Thanks!

Comments are closed.