Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Learn WinUI 3

You're reading from   Learn WinUI 3 Leverage WinUI and the Windows App SDK to create modern Windows applications with C# and XAML

Arrow left icon
Product type Paperback
Published in Oct 2023
Publisher Packt
ISBN-13 9781805120063
Length 386 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Alvin Ashcraft Alvin Ashcraft
Author Profile Icon Alvin Ashcraft
Alvin Ashcraft
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Part 1:Introduction to WinUI and Windows Applications FREE CHAPTER
2. Chapter 1: Introduction to WinUI 3. Chapter 2: Configuring the Development Environment and Creating the Project 4. Chapter 3: MVVM for Maintainability and Testability 5. Chapter 4: Advanced MVVM Concepts 6. Chapter 5: Exploring WinUI Controls 7. Chapter 6: Leveraging Data and Services 8. Part 2:Extending WinUI and Modernizing Applications
9. Chapter 7: Fluent Design System for Windows Applications 10. Chapter 8: Adding Windows Notifications to WinUI Applications 11. Chapter 9: Enhancing Applications with Community Toolkits 12. Chapter 10: Accelerating App Development with Template Studio 13. Part 3:Build and Deploy on Windows and Beyond
14. Chapter 11: Debugging WinUI Applications with Visual Studio 15. Chapter 12: Hosting a Blazor Application in WinUI 16. Chapter 13: Take Your App Cross-Platform with Uno Platform 17. Chapter 14: Packaging and Deploying WinUI Applications 18. Index 19. Other Books You May Enjoy

Using DI with ViewModel classes

Most of the popular MVVM frameworks today include a DI container to manage dependencies. Because .NET now includes its own DI container, we will use that one. The .NET team has incorporated the DI container that used to be bundled with ASP.NET Core. It’s both lightweight and easy to use. Luckily, this container is now available to all types of .NET projects via a NuGet package:

  1. Open the project from the previous chapter or use the project in the Start folder in the GitHub repository for this chapter. In the MyMediaCollection project, open NuGet Package Manager and search for Microsoft.Extensions.Hosting:
Figure 4.1 – Microsoft’s DI NuGet package

Figure 4.1 – Microsoft’s DI NuGet package

  1. Select the package and install the latest stable version. After the installation completes, close the NuGet Package Manager tab and open App.xaml.cs. We will make a few changes here to start using the DI container.

    The DI container implements DI through interfaces called IHostBuilder and IServiceCollection. As the names imply, they are intended to create a collection of services for the application through a shared host. However, we can add any type of class to the container. Its use is not restricted to services. IServiceCollection builds the container, implementing the IServiceProvider interface. In the following steps, you will add support for DI to the application.

  2. The first thing you should do is add a public property to the App class that makes the host container available to the project:
    public static IHost HostContainer { get; private set;
    }

    Here, get is public, but the property has a private set accessor. This restricts the creation of the container to the App class. Don’t forget to add the required using statements to the code:

    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
  3. The next step is to create a new method that initializes the container, sets it to the public property, and adds our first dependency:
    private void RegisterComponents()
    {
        HostContainer = Host.CreateDefaultBuilder()
            .ConfigureServices(services =>
        {
            services.AddTransient<MainViewModel>();
        }).Build();
    }

    In the new RegisterComponents method, we are creating HostContainer and its service collection, registering MainViewModel as a transient (one instance per container request) object, and using the Build method to create and return the DI container. Although it’s not strictly required, when adding multiple types to the container, it’s a good practice to add dependent objects to the service collection first. We’ll be adding more items to the container soon.

  4. Finally, you will call RegisterComponents before creating the instance of MainWindow in the App.OnLaunched event handler:
    protected override void
    OnLaunched(LaunchActivatedEventArgs args)
    {
        RegisterComponents();
        m_window = new MainWindow();
        m_window.Activate();
    }

That’s all the code needed to create and expose the DI container to the application. Now that we are delegating the creation of MainViewModel to the container, you can remove the property that exposes a static instance of MainViewModel from the App class.

Using the ViewModel controlled by the container is simple. Go ahead and open MainWindow.xaml.cs and update the ViewModel property to remove the initialization. Then, set the value of the ViewModel property using HostContainer.Services.GetService from the App class before the call to InitializeComponent:

public MainWindow()
{
    ViewModel = App.HostContainer.Services
      .GetService<MainViewModel>();
    this.InitializeComponent();
}
public MainViewModel ViewModel;

If you build and run the application now, it will work just as it did before. However, now our MainViewModel instance will be registered in the App class and managed by the container. As new models, view models, services, and other dependencies are added to the project, they can be added to the HostContainer in the RegisterComponents method.

We will be adding page navigation to the app later in this chapter. First, let’s discuss the event-to-command pattern.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime