MAUI
MAUI
ms/maui-ebook
EDITION v2.0
PUBLISHED BY
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any
form or by any means without the written permission of the publisher.
This book is provided “as-is” and expresses the author’s views and opinions. The views, opinions, and
information expressed in this book, including URL and other Internet website references, may change
without notice.
Some examples depicted herein are provided for illustration only and are fictitious. No real association
or connection is intended or should be inferred.
Microsoft and the trademarks listed at https://www.microsoft.com on the “Trademarks” webpage are
trademarks of the Microsoft group of companies.
All other marks and logos are property of their respective owners.
Authors:
Reviewers:
Acknowledgments
This book originated from the excellent Enterprise Application Patterns using Xamarin.Forms eBook by
David Britch and Javier Suarez Ruiz. Without their hard work, detailed information, and excellent
examples, this book would not be possible.
Introduction
Enterprise applications face a number of difficult problems to solve including ever changing business
requirements, the need for quick turn around time, support for multiple platforms, and integration
with multiple systems. Due to the varying nature of these problems, it’s important that our
application’s architecture allows it to be modular, modifiable and extensible over time.
This book takes provides real world solutions for addressing these issues when building an enterprise
application using .NET MAUI. This book uses a pre-built .NET MAUI application that serves as the
front-end of an online eCommerce application as a reference and a guide for common enterprise
design patterns. This book covers topics such as the MVVM pattern, dependency injection, navigation,
configuration, the loose-coupling of components and additional enterprise concerns. The content of
this book is helpful for anyone looking to build a new application for this business or looking to solve
the problems of applications that evolve over time.
Additional resources
For official .NET MAUI content, see .NET MAUI docs. .NET MAUI is developed as an open-source
project and is available on GitHub at dotnet/maui. For code samples developed with .NET MAUI, see
the dotnet/maui-samples repo.
Contents
Purpose..................................................................................................................................... 1
What’s left out of this guide’s scope ................................................................................................................................ 1
Summary ..................................................................................................................................................................................... 8
View ....................................................................................................................................................................................... 10
ViewModel .......................................................................................................................................................................... 11
Model .................................................................................................................................................................................... 11
Summary .................................................................................................................................................................................. 20
i Contents
Introduction to dependency injection .......................................................................................................................... 21
Registration ............................................................................................................................................................................. 23
Resolution ................................................................................................................................................................................ 25
Summary .................................................................................................................................................................................. 26
Defining a message.............................................................................................................................................................. 29
Subscribing to a message.................................................................................................................................................. 30
Summary .................................................................................................................................................................................. 31
Navigation.............................................................................................................................. 32
Navigating between pages ............................................................................................................................................... 33
Summary .................................................................................................................................................................................. 38
Validation ............................................................................................................................... 39
Specifying validation rules ................................................................................................................................................ 40
Summary .................................................................................................................................................................................. 45
ii Contents
Creating a Settings Interface ............................................................................................................................................ 46
Summary .................................................................................................................................................................................. 49
Containerization .................................................................................................................................................................... 53
Summary .................................................................................................................................................................................. 59
Increasing resilience............................................................................................................................................................. 70
Summary .................................................................................................................................................................................. 72
iii Contents
Configuring clients .......................................................................................................................................................... 77
Signing-in ............................................................................................................................................................................ 80
Signing-out ......................................................................................................................................................................... 83
Authorization .......................................................................................................................................................................... 84
Summary .................................................................................................................................................................................. 87
ObservableObject ................................................................................................................................................................. 89
Summary .................................................................................................................................................................................. 93
Testing validation.................................................................................................................................................................. 98
Summary .................................................................................................................................................................................. 99
iv Contents
CHAPTER 1
Purpose
This eBook provides guidance on building cross-platform enterprise apps using .NET MAUI. .NET
MAUI is a cross-platform UI toolkit that allows developers to easily create native user interface layouts
that can be shared across platforms, including iOS, macOS, Android, and Windows. It provides a
comprehensive solution for Business to Employee (B2E), Business to Business (B2B), and Business to
Consumer (B2C) apps, providing the ability to share code across all target platforms and helping to
lower the total cost of ownership (TCO).
The guide provides architectural guidance for developing adaptable, maintainable, and testable .NET
MAUI enterprise apps. Guidance is provided on how to implement MVVM, dependency injection,
navigation, validation, and configuration management, while maintaining loose coupling. In addition,
there’s also guidance on performing authentication and authorization with IdentityServer, accessing
data from containerized microservices, and unit testing.
The guide comes with source code for the eShop multi-platform app, and source code for the eShop
reference app. The eShop multi-platform app is a cross-platform enterprise app developed using .NET
MAUI, which connects to a series of containerized microservices known as the eShop reference app.
However, the eShop multi-platform app can be configured to consume data from mock services for
those who wish to avoid deploying the containerized microservices.
A secondary audience is technical decision-makers who would like to receive an architectural and
technology overview before deciding on what approach to select for cross-platform enterprise app
development using .NET MAUI.
1 CHAPTER 1 | Purpose
How to use this guide
This guide focuses on building cross-platform enterprise apps using .NET MAUI. As such, it should be
read in its entirety to provide a foundation of understanding such apps and their technical
considerations. The guide and its sample app can also serve as a starting point or reference for
creating a new enterprise app. Use the associated sample app as a template for the new app or see
how to organize an app’s component parts. Then, refer back to this guide for architectural guidance.
Feel free to forward this guide to team members to help ensure a common understanding of cross-
platform enterprise app development using .NET MAUI. Having everybody working from a common
set of terminologies and underlying principles will help ensure a consistent application of architectural
patterns and practices.
2 CHAPTER 1 | Purpose
CHAPTER 2
Introduction to .NET MAUI
Regardless of platform, developers of enterprise apps face several challenges:
Many enterprise apps are sufficiently complex to require more than one developer. It can be a
significant challenge to decide how to design an app so that multiple developers can work effectively
on different pieces of the app independently, while ensuring that the pieces come together seamlessly
when integrated into the app.
The traditional approach to designing and building an app results in what is referred to as a
monolithic app, where components are tightly coupled with no clear separation between them.
Typically, this monolithic approach leads to apps that are difficult and inefficient to maintain, because
it can be difficult to resolve bugs without breaking other components in the app, and it can be
difficult to add new features or to replace existing features.
An effective remedy for these challenges is to partition an app into discrete, loosely coupled
components that can be easily integrated together into an app. Such an approach offers several
benefits:
Sample application
This guide includes a sample application, eShop, that’s an online store that includes the following
functionality:
The multi-platform app consumes the backend services provided by the eShop reference application.
However, it can be configured to consume data from mock services for those who wish to avoid
deploying the backend services.
The eShop multi-platform app exercises the following .NET MAUI functionality:
In addition, unit tests are provided for some of the classes in the eShop multi-platform app.
While this project has all of its components stored in a singular project, it is worth considering
separating it into multiple projects based on your needs. For example, if you have multiple
implementations of service providers based off of a service with their own dependencies, it may make
sense to break those service provider implementations out into their own separate project. Good
candidates for project separation include shared models, service implementations, api client
components, database or caching layers. Any place where you feel that the business could re-use a
component in another project is a potential candidate for separation. These projects can then be
packaged via NuGet for easy distribution and versioning.
All of the projects use folders to organize the source code and other resources into categories. The
classes from the eShop multi-platform app can be re-used in any .NET MAUI app with little or no
modification.
eShop project
The eShop project contains the following folders:
Folder Description
Animations Contains classes that enable animations to be consumed in XAML.
Behaviors Contains behaviors that are exposed to view classes.
Summary
Microsoft’s cross-platform multi-platform app development tools and platforms provide a
comprehensive solution for B2E, B2B, and B2C mobile client apps, providing the ability to share code
across all target platforms (iOS, macOS, Android, and Windows) and helping to lower the total cost of
ownership. Apps can share their user interface and app logic code, while retaining the native platform
look and feel.
Developers of enterprise apps face several challenges that can alter the architecture of the app during
development. Therefore, it’s important to build an app so that it can be modified or extended over
time. Designing for such adaptability can be difficult, but typically involves partitioning an app into
discrete, loosely coupled components that can be easily integrated together into an app.
The MVVM pattern helps cleanly separate an application’s business and presentation logic from its
user interface (UI). Maintaining a clean separation between application logic and the UI helps address
numerous development issues and makes an application easier to test, maintain, and evolve. It can
also significantly improve code re-use opportunities and allows developers and UI designers to
collaborate more easily when developing their respective parts of an app.
In addition to understanding the responsibilities of each component, it’s also important to understand
how they interact. At a high level, the view “knows about” the view model, and the view model “knows
about” the model, but the model is unaware of the view model, and the view model is unaware of the
view. Therefore, the view model isolates the view from the model, and allows the model to evolve
independently of the view.
View
The view is responsible for defining the structure, layout, and appearance of what the user sees on
screen. Ideally, each view is defined in XAML, with a limited code-behind that does not contain
business logic. However, in some cases, the code-behind might contain UI logic that implements
visual behavior that is difficult to express in XAML, such as animations.
Tip
Ensure that the view models are responsible for defining logical state changes that affect some
aspects of the view’s display, such as whether a command is available, or an indication that an
operation is pending. Therefore, enable and disable UI elements by binding to view model properties,
rather than enabling and disabling them in code-behind.
There are several options for executing code on the view model in response to interactions on the
view, such as a button click or item selection. If a control supports commands, the control’s Command
property can be data-bound to an ICommand property on the view model. When the control’s
command is invoked, the code in the view model will be executed. In addition to commands,
behaviors can be attached to an object in the view and can listen for either a command to be invoked
or the event to be raised. In response, the behavior can then invoke an ICommand on the view model
or a method on the view model.
Tip
Multi-platform apps should keep the UI thread unblocked to improve the user’s perception of
performance. Therefore, in the view model, use asynchronous methods for I/O operations and raise
events to asynchronously notify views of property changes.
The view model is also responsible for coordinating the view’s interactions with any model classes that
are required. There’s typically a one-to-many relationship between the view model and the model
classes. The view model might choose to expose model classes directly to the view so that controls in
the view can data bind directly to them. In this case, the model classes will need to be designed to
support data binding and change notification events.
Each view model provides data from a model in a form that the view can easily consume. To
accomplish this, the view model sometimes performs data conversion. Placing this data conversion in
the view model is a good idea because it provides properties that the view can bind to. For example,
the view model might combine the values of two properties to make it easier to display by the view.
Tip
It’s also possible to use converters as a separate data conversion layer that sits between the view
model and the view. This can be necessary, for example, when data requires special formatting that
the view model doesn’t provide.
In order for the view model to participate in two-way data binding with the view, its properties must
raise the PropertyChanged event. View models satisfy this requirement by implementing the
INotifyPropertyChanged interface, and raising the PropertyChanged event when a property is
changed.
Model
Model classes are non-visual classes that encapsulate the app’s data. Therefore, the model can be
thought of as representing the app’s domain model, which usually includes a data model along with
business and validation logic. Examples of model objects include data transfer objects (DTOs), Plain
Old CLR Objects (POCOs), and generated entity and proxy objects.
With view first composition the app is conceptually composed of views that connect to the view
models they depend on. The primary benefit of this approach is that it makes it easy to construct
loosely coupled, unit testable apps because the view models have no dependence on the views
themselves. It’s also easy to understand the structure of the app by following its visual structure,
rather than having to track code execution to understand how classes are created and associated. In
addition, view first construction aligns with the Microsoft Maui’s navigation system that’s responsible
for constructing pages when navigation occurs, which makes a view model first composition complex
and misaligned with the platform.
With view model first composition, the app is conceptually composed of view models, with a service
responsible for locating the view for a view model. View model first composition feels more natural to
some developers, since the view creation can be abstracted away, allowing them to focus on the
logical non-UI structure of the app. In addition, it allows view models to be created by other view
models. However, this approach is often complex, and it can become difficult to understand how the
various parts of the app are created and associated.
Tip
The binding of views to a property in a data source should be the view’s principal dependency on its
corresponding view model. Specifically, don’t reference view types, such as Button and ListView, from
view models. By following the principles outlined here, view models can be tested in isolation,
therefore reducing the likelihood of software defects by limiting scope.
The following sections discuss the main approaches to connecting view models to views.
<ContentPage xmlns:local="clr-namespace:eShop">
<ContentPage.BindingContext>
This declarative construction and assignment of the view model by the view has the advantage that
it’s simple, but has the disadvantage that it requires a default (parameter-less) constructor in the view
model.
public LoginView()
{
InitializeComponent();
BindingContext = new LoginViewModel(navigationService);
}
The programmatic construction and assignment of the view model within the view’s code-behind has
the advantage that it’s simple. However, the main disadvantage of this approach is that the view
needs to provide the view model with any required dependencies. Using a dependency injection
container can help to maintain loose coupling between the view and view model. For more
information, see Dependency injection.
App’s should be architected for the correct use of property change notification, by meeting the
following requirements:
• Always raising a PropertyChanged event if a public property’s value changes. Do not assume
that raising the PropertyChanged event can be ignored because of knowledge of how XAML
binding occurs.
• Always raising a PropertyChanged event for any calculated properties whose values are used
by other properties in the view model or model.
• Always raising the PropertyChanged event at the end of the method that makes a property
change, or when the object is known to be in a safe state. Raising the event interrupts the
.NET MAUI’s BindableObject class implements the INotifyPropertyChanged interface, and provides an
OnPropertyChanged method. The ExtendedBindableObject class provides the RaisePropertyChanged
method to invoke property change notification, and in doing so uses the functionality provided by the
BindableObject class.
View model classes can then derive from the ExtendedBindableObject class. Therefore, each view
model class uses the RaisePropertyChanged method in the ExtendedBindableObject class to provide
property change notification. The following code example shows how the eShop multi-platform app
invokes property change notification by using a lambda expression:
Using a lambda expression in this way involves a small performance cost because the lambda
expression has to be evaluated for each call. Although the performance cost is small and would not
typically impact an app, the costs can accrue when there are many change notifications. However, the
benefit of this approach is that it provides compile-time type safety and refactoring support when
renaming properties.
MVVM Frameworks
The MVVM pattern is well established in .NET, and the community has created many frameworks
which help ease this development. Each framework provides a different set of features, but it is
standard for them to provide a common view model with an implementation of the
INotifyPropertyChanged interface. Additional features of MVVM frameworks include custom
commands, navigation helpers, dependency injection/service locator components, and UI platform
integration. While it is not necessary to use these frameworks, they can speed up and standardize
your development. The eShop multi-platform app uses the .NET Community MVVM Toolkit. When
choosing a framework, you should consider your application’s needs and your team’s strengths. The
list below includes some of the more common MVVM frameworks for .NET MAUI.
Commands provide a convenient way to represent actions that can be bound to controls in the UI.
They encapsulate the code that implements the action and help to keep it decoupled from its visual
representation in the view. This way, your view models become more portable to new platforms, as
they do not have a direct dependency on events provided by the platform’s UI framework. .NET MAUI
includes controls that can be declaratively connected to a command, and these controls will invoke
the command when the user interacts with the control.
Behaviors also allow controls to be declaratively connected to a command. However, behaviors can be
used to invoke an action that’s associated with a range of events raised by a control. Therefore,
behaviors address many of the same scenarios as command-enabled controls, while providing a
greater degree of flexibility and control. In addition, behaviors can also be used to associate command
objects or methods with controls that were not specifically designed to interact with commands.
Note
While it’s possible to expose the actual implementation of the ICommand interface that your view
model uses (for example, Command<T> or RelayCommand), it is recommended to expose your
commands publicly as ICommand. This way, if you ever need to change the implementation at a later
date, it can easily be swapped out.
The ICommand interface defines an Execute method, which encapsulates the operation itself, a
CanExecute method, which indicates whether the command can be invoked, and a
CanExecuteChanged event that occurs when changes occur that affect whether the command should
execute. In most cases, we will only supply the Execute method for our commands. For a more
detailed overview of ICommand, refer to the Commanding documentation for .NET MAUI.
Provided with .NET MAUI are the Command and Command<T> classes that implement the
ICommand interface, where T is the type of the arguments to Execute and CanExecute. Command and
Command<T> are basic implementations that provide the minimal set of functionality needed for the
ICommand interface.
Note
Many MVVM frameworks offer more feature rich implementations of the ICommand interface.
The Command or Command<T> constructor requires an Action callback object that’s called when the
ICommand.Execute method is invoked. The CanExecute method is an optional constructor parameter,
and is a Func that returns a bool.
The eShop multi-platform app uses the RelayCommand and AsyncRelayCommand. The primary
benefit for modern applications is that the AsyncRelayCommand provides better functionality for
asynchronous operations.
The following code shows how a Command instance, which represents a register command, is
constructed by specifying a delegate to the Register view model method:
The command is exposed to the view through a property that returns a reference to an ICommand.
When the Execute method is called on the Command object, it simply forwards the call to the method
in the view model via the delegate that was specified in the Command constructor. An asynchronous
method can be invoked by a command by using the async and await keywords when specifying the
command’s Execute delegate. This indicates that the callback is a Task and should be awaited. For
Parameters can be passed to the Execute and CanExecute actions by using the
AsyncRelayCommand<T> class to instantiate the command. For example, the following code shows
how an AsyncRelayCommand<T> instance is used to indicate that the NavigateAsync method will
require an argument of type string:
...
NavigateCommand = new AsyncRelayCommand<string>(NavigateAsync);
In both the RelayCommand and RelayCommand<T> classes, the delegate to the CanExecute method
in each constructor is optional. If a delegate isn’t specified, the Command will return true for
CanExecute. However, the view model can indicate a change in the command’s CanExecute status by
calling the ChangeCanExecute method on the Command object. This causes the CanExecuteChanged
event to be raised. Any UI controls bound to the command will then update their enabled status to
reflect the availability of the data-bound command.
A command parameter can also be optionally defined using the CommandParameter property. The
type of the expected argument is specified in the Execute and CanExecute target methods. The
TapGestureRecognizer will automatically invoke the target command when the user interacts with the
attached control. The CommandParameter, if provided, will be passed as the argument to the
command’s Execute delegate.
Implementing behaviors
Behaviors allow functionality to be added to UI controls without having to subclass them. Instead, the
functionality is implemented in a behavior class and attached to the control as if it was part of the
control itself. Behaviors enable you to implement code that you would typically have to write as code-
behind, because it directly interacts with the API of the control, in such a way that it can be concisely
A behavior that’s attached to a control through attached properties is known as an attached behavior.
The behavior can then use the exposed API of the element to which it is attached to add functionality
to that control, or other controls, in the visual tree of the view.
A .NET MAUI behavior is a class that derives from the Behavior or Behavior<T> class, where T is the
type of the control to which the behavior should apply. These classes provide OnAttachedTo and
OnDetachingFrom methods, which should be overridden to provide logic that will be executed when
the behavior is attached to and detached from controls.
In the eShop multi-platform app, the BindableBehavior<T> class derives from the Behavior<T> class.
The purpose of the BindableBehavior<T> class is to provide a base class for .NET MAUI behaviors that
require the BindingContext of the behavior to be set to the attached control.
The BindableBehavior<T> class provides an overridable OnAttachedTo method that sets the
BindingContext of the behavior, and an overridable OnDetachingFrom method that cleans up the
BindingContext.
The eShop multi-platform app includes an EventToCommandBehavior class which is provided by the
MAUI Community toolkit. EventToCommandBehavior executes a command in response to an event
occurring. This class derives from the BaseBehavior<View> class so that the behavior can bind to and
execute an ICommand specified by a Command property when the behavior is consumed. The
following code example shows the EventToCommandBehavior class:
/// <summary>
/// The <see cref="EventToCommandBehavior"/> is a behavior that allows the user to invoke a
<see cref="ICommand"/> through an event. It is designed to associate Commands to events
exposed by controls that were not designed to support Commands. It allows you to map any
arbitrary event on a control to a Command.
/// </summary>
public class EventToCommandBehavior : BaseBehavior<VisualElement>
{
// Omitted for brevity...
/// <inheritdoc/>
protected override void OnAttachedTo(VisualElement bindable)
{
base.OnAttachedTo(bindable);
RegisterEvent();
}
/// <inheritdoc/>
protected override void OnDetachingFrom(VisualElement bindable)
{
UnregisterEvent();
base.OnDetachingFrom(bindable);
}
void RegisterEvent()
{
eventInfo = View.GetType()?.GetRuntimeEvent(eventName) ??
throw new ArgumentException($"{nameof(EventToCommandBehavior)}: Couldn't
resolve the event.", nameof(EventName));
ArgumentNullException.ThrowIfNull(eventInfo.EventHandlerType);
ArgumentNullException.ThrowIfNull(eventHandlerMethodInfo);
eventHandler = eventHandlerMethodInfo.CreateDelegate(eventInfo.EventHandlerType,
this) ??
throw new ArgumentException($"{nameof(EventToCommandBehavior)}: Couldn't create
event handler.", nameof(EventName));
eventInfo.AddEventHandler(View, eventHandler);
}
void UnregisterEvent()
{
if (eventInfo is not null && eventHandler is not null)
{
eventInfo.RemoveEventHandler(View, eventHandler);
}
eventInfo = null;
eventHandler = null;
}
/// <summary>
/// Virtual method that executes when a Command is invoked
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
[Microsoft.Maui.Controls.Internals.Preserve(Conditional = true)]
protected virtual void OnTriggerHandled(object? sender = null, object? eventArgs =
null)
{
var parameter = CommandParameter
?? EventArgsConverter?.Convert(eventArgs, typeof(object), null, null);
The OnAttachedTo and OnDetachingFrom methods are used to register and deregister an event
handler for the event defined in the EventName property. Then, when the event fires, the
OnTriggerHandled method is invoked, which executes the command.
<Entry
IsPassword="True"
Text="{Binding Password.Value, Mode=TwoWay}">
<!-- Omitted for brevity... -->
<Entry.Behaviors>
<mct:EventToCommandBehavior
EventName="TextChanged"
Command="{Binding ValidateCommand}" />
</Entry.Behaviors>
<!-- Omitted for brevity... -->
</Entry>
At runtime, the EventToCommandBehavior will respond to interaction with the Entry. When a user
types into the Entry field, the TextChanged event will fire, which will execute the ValidateCommand in
the LoginViewModel. By default, the event arguments for the event are passed to the command. If
needed, the EventArgsConverter property can be used to convert the EventArgs provided by the event
into a value that the command expects as input.
For more information about behaviors, see Behaviors on the .NET MAUI Developer Center.
Summary
The Model-View-ViewModel (MVVM) pattern helps cleanly separate an application’s business and
presentation logic from its user interface (UI). Maintaining a clean separation between application
logic and the UI helps address numerous development issues and makes an application easier to test,
maintain, and evolve. It can also significantly improve code re-use opportunities and allows
developers and UI designers to collaborate more easily when developing their respective parts of an
app.
Using the MVVM pattern, the UI of the app and the underlying presentation and business logic are
separated into three separate classes: the view, which encapsulates the UI and UI logic; the view
model, which encapsulates presentation logic and state; and the model, which encapsulates the app’s
business logic and data.
By specifying dependencies as interface types, dependency injection enables decoupling the concrete
types from the code that depends on these types. It generally uses a container that holds a list of
registrations and mappings between interfaces and abstract types, and the concrete types that
implement or extend these types.
There are also other types of dependency injection, such as property setter injection and method call
injection, but they are less commonly seen. Therefore, this chapter will focus solely on performing
constructor injection with a dependency injection container.
public ProfileViewModel(
IAppEnvironmentService appEnvironmentService,
IDialogService dialogService,
INavigationService navigationService,
ISettingsService settingsService)
: base(dialogService, navigationService, settingsService)
{
_appEnvironmentService = appEnvironmentService;
_settingsService = settingsService;
The ProfileViewModel constructor receives multiple interface object instances as arguments injected
by another class. The only dependency in the ProfileViewModel class is on the interface types.
Therefore, the ProfileViewModel class doesn’t have any knowledge of the class that’s responsible for
instantiating the interface objects. The class that’s responsible for instantiating the interface objects,
and inserting it into the ProfileViewModel class, is known as the dependency injection container.
• A container removes the need for a class to locate its dependencies and manage its lifetimes.
• A container allows the mapping of implemented dependencies without affecting the class.
• A container facilitates testability by allowing dependencies to be mocked.
• A container increases maintainability by allowing new classes to be easily added to the app.
In the context of a .NET MAUI app that uses MVVM, a dependency injection container will typically be
used for registering and resolving views, registering and resolving view models, and for registering
services and injecting them into view models.
There are many dependency injection containers available in .NET; the eShop multi-platform app uses
Microsoft.Extensions.DependencyInjection to manage the instantiation of views, view models, and
service classes in the app. Microsoft.Extensions.DependencyInjection facilitates building loosely
coupled apps, and provides all of the features commonly found in dependency injection containers,
including methods to register type mappings and object instances, resolve objects, manage object
lifetimes, and inject dependent objects into constructors of objects that it resolves. For more
information about Microsoft.Extensions.DependencyInjection, see Dependency injection in .NET.
In .NET MAUI, the MauiProgram class will call into the CreateMauiApp method to create a
MauiAppBuilder object. The MauiAppBuilder object has a Services property of type IServiceCollection,
which provides a place to register our components, such as views, view models, and services for
dependency injection. Any components registered with the Services property will be provided to the
dependency injection container when the MauiAppBuilder.Build method is called.
At runtime, the container must know which implementation of the services are being requested in
order to instantiate them for the requested objects. In the eShop multi-platform app, the
IAppEnvironmentService, IDialogService , INavigationService, and ISettingsService interfaces need to
be resolved before it can instantiate a ProfileViewModel object. This involves the container performing
the following actions:
• Deciding how to instantiate an object that implements the interface. This is known as
registration.
• Instantiating the object that implements the required interface and the ProfileViewModel
object. This is known as resolution.
Eventually, the app will finish using the ProfileViewModel object, and it will become available for
garbage collection. At this point, the garbage collector should dispose of any short-lived interface
implementations if other classes do not share the same instance.
There are two ways of registering types and objects in the container through code:
• Register a type or mapping with the container. This is known as transient registration. When
required, the container will build an instance of the specified type.
• Register an existing object in the container as a singleton. When required, the container will
return a reference to the existing object.
Note
Dependency injection containers are not always suitable. Dependency injection introduces additional
complexity and requirements that might not be appropriate or useful to small apps. If a class does not
have any dependencies, or is not a dependency for other types, it might not make sense to put it in
the container. In addition, if a class has a single set of dependencies that are integral to the type and
will never change, it might not make sense to put it in the container.
The registration of types requiring dependency injection should be performed in a single method in
an app. This method should be invoked early in the app’s lifecycle to ensure it is aware of the
dependencies between its classes. The eShop multi-platform app performs this the
MauiProgram.CreateMauiApp method. The following code example shows how the eShop multi-
platform app declares the CreateMauiApp in the MauiProgram class:
The MauiApp.CreateBuilder method creates a MauiAppBuilder object that we can use to register our
dependencies. Many dependencies in the eShop multi-platform app need to be registered, so the
extension methods RegisterAppServices, RegisterViewModels, and RegisterViews were created to help
provide an organized and maintainable registration workflow. The following code shows the
RegisterViewModels method:
return mauiAppBuilder;
}
This method receives an instance of MauiAppBuilder, and we can use the Services property to register
our view models. Depending on the needs of your application, you may need to add services with
different lifetimes. The following table provides information on when you may want to choose these
different registration lifetimes:
Method Description
AddSingleton<T> Will create a single instance of the object which
will be remain for the lifetime of the application.
AddTransient<T> Will create a new instance of the object when
requested during resolution. Transient objects
do not have a pre-defined lifetime, but will
typically follow the lifetime of their host.
Note
The view models do not inherit from an interface, so they only need their concrete type provided to
the AddSingleton<T> and AddTransient<T> methods.
The CatalogViewModel is used near the application’s root and should always be available, so
registering it with AddSingleton<T> is beneficial. Other view models, such as CheckoutViewModel
and OrderDetailViewModel are situationally navigated to or are used later in the application. Suppose
you know that you have a component that may not always be used. In that case, if it is memory or
computationally intensive or requires just-in-time data, it may be a better candidate for
AddTransient<T> registration.
Another common way to add services is using the AddSingleton<TService, TImplementation> and
AddTransient<TService, TImplementation> methods. These methods take two input types: the
interface definition and the concrete implementation. This type of registration is best for cases where
you are implementing services based on interfaces. In the code example below, we register our
ISettingsService interface using the SettingsService implementation:
Once all services have been registered, the MauiAppBuilder.Build method should be called to create
our MauiApp and populate our dependency injection container with all the registered services.
Once the Build method has been called, the dependency injection container is immutable and can no
longer be updated or modified. Ensure that all services that you need within your application have
been registered before you call Build.
Resolution
After a type is registered, it can be resolved or injected as a dependency. When a type is being
resolved, and the container needs to create a new instance, it injects any dependencies into the
instance.
This can be helpful if you need to resolve a service from within an Element or from outside of the
constructor of your Element.
Caution
There is a possibility that the Handler property of your Element may be null, so be aware that you may
need to handle those situations. For more information, please refer to Handler lifecycle on the
Microsoft Documentation Center.
If using the Shell control for .NET MAUI, it will implicitly call into the dependency injection container
to create our objects during navigation. When setting up our Shell control, the Routing.RegisterRoute
method will tie a route path to a View as shown in the example below:
Routing.RegisterRoute("Filter", typeof(FiltersView));
During Shell navigation, it will look for registrations of the FiltersView, and if any are found, it will
create that view and inject any dependencies into the constructor. As shown in the code example
below, the CatalogViewModel will be injected into the FiltersView:
namespace eShop.Views;
InitializeComponent();
}
}
Tip
The dependency injection container is great for creating view model instances. If a view model has
dependencies, it will handle the creation and injection of any required services. Just make sure that
you register your view models and any dependencies that they may have with the CreateMauiApp
method in the MauiProgram class.
Summary
Dependency injection enables the decoupling of concrete types from the code that depends on these
types. It typically uses a container that holds a list of registrations and mappings between interfaces
and abstract types, and the concrete types that implement or extend these types.
Events in .NET implement the publish-subscribe pattern and are the most simple approach for a
communication layer between components if loose coupling is not required, such as a control and the
page that contains it. However, the publisher and subscriber lifetimes are coupled by object
references to each other, and the subscriber type must have a reference to the publisher type. This
can create memory management issues, especially when there are short-lived objects that subscribe
to an event of a static or long-lived object. If the event handler isn’t removed, the subscriber will be
kept alive by the reference to it in the publisher, and this will prevent or delay the garbage collection
of the subscriber.
Note
The MVVM Toolkit Messenger is part of the CommunityToolkit.Mvvm package. For information on
how to add the package to your project, see Introduction to the MVVM Toolkit on the Microsoft
Developer Center.
.NET MAUI contains a built-in MessagingCenter class that’s no longer recommended for use. Use the
MVVM Toolkit Messenger instead.
The IMessenger interface allows for multicast publish-subscribe functionality. This means that there
can be multiple publishers that publish a single message, and there can be multiple subscribers
listening to the same message. The image below illustrates this relationship:
There are two implementations of the IMessenger interface that come with the
CommunityToolkit.Mvvm package. The WeakReferenceMessenger uses weak references which can
result in easier cleanup for message subscribers. This is a good option if your subscribers do not have
a clearly defined lifecycle. The StrongReferenceMessenger uses strong references which can result in
better performance and a more clearly controlled lifetime of the subscription. If you have a workflow
with a very controlled lifetime (for example, a subscription that is bound to a page’s OnAppearing and
OnDisappearing methods), the StrongReferenceManager may be a better option, if performance is a
concern. Both of these implementations are available with default implementations ready to use by
referencing either WeakReferenceMessenger.Default or StrongReferenceMessenger.Default.
Note
While the IMessenger interface permits communication between loosely-coupled classes, it does not
offer the only architectural solution to this issue. For example, communication between a view model
and a view can also be achieved by the binding engine and through property change notifications. In
addition, communication between two view models can also be achieved by passing data during
navigation.
The eShop multi-platform app uses the WeakReferenceMessenger class to communicate between
loosely coupled components. The app defines a single message named AddProductMessage. The
AddProductMessage is published by the CatalogViewModel class when an item is added to the
shopping basket. In return, the CatalogView class subscribes to the message and uses this to highlight
the product adds with animation in response.
Marshal to the UI or main thread when performing UI updates. If updates to user interfaces are not
made on this thread, it can cause the application to crash or become unstable.
If a message that’s sent from a background thread is required to update the UI, process the message
on the UI thread in the subscriber by invoking the MainThread.BeginInvokeOnMainThread method.
For more information about Messenger, see Messenger on the Microsoft Developer Center.
Defining a message
IMessenger messages are custom objects that provide custom payloads. The following code example
shows the AddProductMessage message defined within the eShop multi-platform app:
The base class is defined using ValueChangedMessage<T> where T can be of any type needed to
pass data. Both message publishers and subscribers can expect messages of a specific type (for
example, AddProductMessage). This can help ensure that both parties have agreed to a messaging
contract and that the data provided with that contract will be consistent. Additionally, this approach
provides compile-time type safety and refactoring support.
Publishing a message
To publish a message, we will need to use the IMessenger.Send method. This can be accessed most
commonly through WeakReferenceMessenger.Default.Send or
StrongReferenceMessenger.Default.Send. The message sent can be of any object type. The following
code example demonstrates publishing the AddProduct message:
WeakReferenceMessenger.Default.Send(new Messages.AddProductMessage(BadgeCount));
In this example, the Send method specifies provides a new instance of the AddProductMessage object
for downstream subscribers to receive. An additional second token parameter can be added to use
when multiple different subscribers need to receive messages of the same type without receiving the
wrong message.
The Send method will publish the message, and its payload data, using a fire-and-forget approach.
Therefore, the message is sent even if there are no subscribers registered to receive the message. In
this situation, the sent message is ignored.
WeakReferenceMessenger.Default
.Register<CatalogView, Messages.AddProductMessage>(
this,
async (recipient, message) =>
{
await recipient.Dispatcher.DispatchAsync(
async () =>
{
await recipient.badge.ScaleTo(1.2);
await recipient.badge.ScaleTo(1.0);
});
});
In the preceding example, the Register method subscribes to the AddProductMessage message and
executes a callback delegate in response to receiving the message. This callback delegate, specified as
a lambda expression, executes code that updates the UI.
Note
Avoid the use of this within your callback delegate to avoid capturing that object within the delegate.
This can help improve performance. Instead, use the recipient parameter.
If payload data is supplied, don’t attempt to modify the payload data from within a callback delegate
because several threads could be accessing the received data simultaneously. In this scenario, the
payload data should be immutable to avoid concurrency errors.
WeakReferenceMessenger.Default.Unregister<Messages.AddProductMessage>(this);
Note
In this example, it isn’t fully necessary to call Unregister as the WeakReferenceMessenger will allow
unused objects to be garbage collected. If the StrongReferenceMessenger were used, it would be
advised to call Unregister for any subscriptions that are no longer in use.
In this example, the Unsubscribe method syntax specifies the type argument of the message and the
recipient object that is listening for messages.
• Identifying the view to be navigated to using an approach that does not introduce tight
coupling and dependencies between views.
• Coordinating the process by which the view to be navigated to is instantiated and initialized.
When using MVVM, the view and view-model need to be instantiated and associated with
each other via the view’s binding context. When an app is using a dependency injection
container, the instantiation of views and view-models might require a specific construction
mechanism.
• Whether to perform view-first navigation, or view-model-first navigation. With view-first
navigation, the page to navigate to refers to the name of the view type. During navigation,
the specified view is instantiated, along with its corresponding view-model and other
dependent services. An alternative approach is to use view-model-first navigation, where the
page to navigate to refers to the name of the view-model type.
• Determining how to cleanly separate the navigational behavior of the app across the views
and view-models. The MVVM pattern separates the app’s UI and its presentation and business
logic, but it doesn’t provide a direct mechanism for tying them together. However, the
navigation behavior of an app will often span the UI and presentation parts of the app. The
user will often initiate navigation from a view, and the view will be replaced as a result of the
navigation. However, navigation might often also need to be initiated or coordinated from
within the view-model.
• Determining how to pass parameters during navigation for initialization purposes. For
example, if the user navigates to a view to update order details, the order data will have to be
passed to the view so that it can display the correct data.
• Coordinating navigation to ensure that specific business rules are obeyed. For example, users
might be prompted before navigating away from a view so that they can correct any invalid
data or be prompted to submit or discard any data changes that were made within the view.
This chapter addresses these challenges by presenting a navigation service class named
MauiNavigationService that’s used to perform view-model-first page navigation.
Note
The MauiNavigationService used by the app is simplistic and does not cover all possible navigation
types. The types of navigation needed by your application may require additional functionality.
32 CHAPTER 6 | Navigation
Navigating between pages
Navigation logic can reside in a view’s code-behind or a data-bound view-model. While placing
navigation logic in a view might be the most straightforward approach, it is not easily testable
through unit tests. Putting navigation logic in view-model classes means that the logic can be verified
through unit tests. In addition, the view-model can then implement logic to control navigation to
ensure that certain business rules are enforced. For example, an app might not allow the user to
navigate away from a page without first ensuring that the entered data is valid.
A navigation service is typically invoked from view-models, in order to promote testability. However,
navigating to views from view-models would require the view-models to reference views, and
particularly views that the active view-model isn’t associated with, which is not recommended.
Therefore, the MauiNavigationService presented here specifies the view-model type as the target to
navigate to.
The eShop multi-platform app uses the MauiNavigationService class to provide view-model-first
navigation. This class implements the INavigationService interface, which is shown in the following
code example:
Task PopAsync();
}
This interface specifies that an implementing class must provide the following methods:
Method Purpose
InitializeAsync Performs navigation to one of two pages when
the app is launched.
NavigateToAsync(string route, Performs hierarchical navigation to a specified
IDictionary<string, object> routeParameters = page using a registered navigation route. Can
null) optionally pass named route parameters to use
for processing on the destination page
PopAsync Removes the current page from the navigation
stack.
Note
An INavigationService interface would usually also specify a GoBackAsync method, which is used to
programmatically return to the previous page in the navigation stack. However, this method is missing
from the eShop multi-platform app because it’s not required.
33 CHAPTER 6 | Navigation
Creating the MauiNavigationService instance
The MauiNavigationService class, which implements the INavigationService interface, is registered as a
singleton with the dependency injection container in the MauiProgram.CreateMauiApp() method, as
demonstrated in the following code example:
mauiAppBuilder.Services.AddSingleton<INavigationService, MauiNavigationService>();;
The INavigationService interface can then be resolved by adding it to the constructor of our views and
view-models, as demonstrated in the following code example:
This returns a reference to the MauiNavigationService object that’s stored in the dependency injection
container.
Navigation is performed inside view-model classes by invoking one of the NavigateToAsync methods,
specifying the route path for the page being navigated to, as demonstrated in the following code
example:
await NavigationService.NavigateToAsync("//Main");
The following code example shows the NavigateToAsync method provided by the
MauiNavigationService class:
The .NET MAUI Shell control is already familiar with route-based navigation, so the NavigateToAsync
method works to mask this functionality. The NavigateToAsync method allows navigation data to be
34 CHAPTER 6 | Navigation
specified as an argument that’s passed to the view-model being navigated to, where it’s typically used
to perform initialization. For more information, see Passing parameters during navigation.
Important
There are multiple ways to perform navigation in .NET MAUI. The MauiNavigationService is specifically
build to work with Shell. If you are using a NavigationPage or TabbedPage or a different navigation
mechanism, this routing service would have to be updated to work using those components.
In order to register routes for the MauiNavigationService we need to supply route information from
XAML or in the code-behind. The following example shows registration of routes via XAML.
<FlyoutItem >
<ShellContent x:Name="login" ContentTemplate="{DataTemplate views:LoginView}"
Route="Login" />
</FlyoutItem>
In this example, the ShellContent and TabBar user interface objects are setting their Route property.
This is the preferred method of registering routes for user interface objects that are controlled by a
Shell.
If we have objects that will be added to the navigation stack at a later time, then we will need to add
those via code-behind. The following example show registration of routes in code-behind.
Routing.RegisterRoute("Filter", typeof(FiltersView));
Routing.RegisterRoute("Basket", typeof(BasketView));
In code-behind, we will call the Routing.RegisterRoute method which takes a route name as the first
parameter and a view type as the second parameter. When a view-model uses the NavigationService
property to navigate, the application’s Shell object will look for registered routes and push them onto
the navigation stack.
After the view is created and navigated to, the ApplyQueryAttributes and InitializeAsync methods of
the view’s associated view-model are executed. For more information, see Passing parameters during
navigation.
35 CHAPTER 6 | Navigation
Navigating when the app is launched
When the app is launched, a Shell object is set as the root view of the application. Once set, the Shell
will be used to control route registration and will be present at the root of our application going
forward. Once the Shell has been created, we can wait for it to be attached to the application using
the OnParentSet method to initialize our navigation route. The following code example shows this
method:
The method uses an instance of INavigationService which is provided the constructor from
dependency injection and invokes its InitializeAsync method.
The //Main/Catalog route is navigated to if the app has a cached access token, which is used for
authentication. Otherwise, the //Login route is navigated to.
For example, the ProfileViewModel class contains an OrderDetailCommand that’s executed when the
user selects an order on the ProfileView page. In turn, this executes the OrderDetailAsync method,
which is shown in the following code example:
await NavigationService.NavigateToAsync(
"OrderDetail",
36 CHAPTER 6 | Navigation
new Dictionary<string, object>{ { "OrderNumber", order.OrderNumber } });
}
This method invokes navigation to the OrderDetail route, passing order number information the order
that the user selected. When the dependency injection framework creates the OrderDetailView for the
OrderDetail route along with the OrderDetailViewModel class which is assigned to the view’s
BindingContext. The OrderDetailViewModel has an attribute added to it that allows it to receive data
from the navigation service as shown in the code example below.
[QueryProperty(nameof(OrderNumber), "OrderNumber")]
public class OrderDetailViewModel : ViewModelBase
{
public int OrderNumber { get; set; }
}
The QueryProperty attribute allows us to provide a parameter for a property to map values to and a
key to find values from the query parameters dictionary. In this example, the key “OrderNumber” and
order number value were provided during the NavigateToAsync call. The view-model found the
“OrderNumber” key and mapped the value to the OrderNumber property. The OrderNumber property
can then be used at a later time to retrieve the full order details from the OrderService instance.
<WebView>
<WebView.Behaviors>
<behaviors:EventToCommandBehavior
EventName="Navigating"
EventArgsConverter="{StaticResource WebNavigatingEventArgsConverter}"
Command="{Binding NavigateCommand}" />
</WebView.Behaviors>
</WebView>
At runtime, the EventToCommandBehavior will respond to interaction with the WebView. When the
WebView navigates to a web page, the Navigating event will fire, which will execute the
NavigateCommand in the LoginViewModel. By default, the event arguments for the event are passed
to the command. This data is converted as it’s passed between source and target by the converter
specified in the EventArgsConverter property, which returns the Url from the
WebNavigatingEventArgs. Therefore, when the NavigationCommand is executed, the Url of the web
page is passed as a parameter to the registered Action.
In turn, the NavigationCommand executes the NavigateAsync method, which is shown in the
following code example:
37 CHAPTER 6 | Navigation
_settingsService.AuthAccessToken = accessToken;
_settingsService.AuthIdToken = authResponse.IdentityToken;
await NavigationService.NavigateToAsync("//Main/Catalog");
}
}
This method invokes NavigationService route the application to the //Main/Catalog route.
Summary
.NET MAUI includes support for page navigation, which typically results from the user’s interaction
with the UI, or from the app itself, as a result of internal logic-driven state changes. However,
navigation can be complex to implement in apps that use the MVVM pattern.
38 CHAPTER 6 | Navigation
CHAPTER 7
Validation
Any app that accepts input from users should ensure that the input is valid. An app could, for
example, check for input that contains only characters in a particular range, is of a certain length, or
matches a particular format. Without validation, a user can supply data that causes the app to fail.
Proper validation enforces business rules and could help to prevent an attacker from injecting
malicious data.
In the context of the Model-View-ViewModel (MVVM) pattern, a view model or model will often be
required to perform data validation and signal any validation errors to the view so that the user can
correct them. The eShop multi-platform app performs synchronous client-side validation of view
model properties and notifies the user of any validation errors by highlighting the control that
contains the invalid data, and by displaying error messages that inform the user of why the data is
invalid. The image below shows the classes involved in performing validation in the eShop multi-
platform app.
View model properties that require validation are of type ValidatableObject<T>, and each
ValidatableObject<T> instance has validation rules added to its Validations property. Validation is
39 CHAPTER 7 | Validation
invoked from the view model by calling the Validate method of the ValidatableObject<T> instance,
which retrieves the validation rules and executes them against the ValidatableObject<T>.Value
property. Any validation errors are placed into the Errors property of the ValidatableObject<T>
instance, and the IsValid property of the ValidatableObject<T> instance is updated to indicate
whether the validation succeeded or failed. The following code shows the implementation of the
ValidatableObject<T>:
using CommunityToolkit.Mvvm.ComponentModel;
namespace eShop.Validations;
public class ValidatableObject<T> : ObservableObject, IValidity
{
private IEnumerable<string> _errors;
private bool _isValid;
private T _value;
public List<IValidationRule<T>> Validations { get; } = new();
public IEnumerable<string> Errors
{
get => _errors;
private set => SetProperty(ref _errors, value);
}
public bool IsValid
{
get => _isValid;
private set => SetProperty(ref _isValid, value);
}
public T Value
{
get => _value;
set => SetProperty(ref _value, value);
}
public ValidatableObject()
{
_isValid = true;
_errors = Enumerable.Empty<string>();
}
public bool Validate()
{
Errors = Validations
?.Where(v => !v.Check(Value))
?.Select(v => v.ValidationMessage)
?.ToArray()
?? Enumerable.Empty<string>();
IsValid = !Errors.Any();
return IsValid;
}
}
Property change notification is provided by the ObservableObject class, and so an Entry control can
bind to the IsValid property of ValidatableObject<T> instance in the view model class to be notified of
whether or not the entered data is valid.
40 CHAPTER 7 | Validation
public interface IValidationRule<T>
{
string ValidationMessage { get; set; }
bool Check(T value);
}
This interface specifies that a validation rule class must provide a boolean Check method that is used
to perform the required validation, and a ValidationMessage property whose value is the validation
error message that will be displayed if validation fails.
The following code example shows the IsNotNullOrEmptyRule<T> validation rule, which is used to
perform validation of the username and password entered by the user on the LoginView when using
mock services in the eShop multi-platform app:
The Check method returns a boolean indicating whether the value argument is null, empty, or consists
only of whitespace characters.
Although not used by the eShop multi-platform app, the following code example shows a validation
rule for validating email addresses:
The Check method returns a boolean indicating whether or not the value argument is a valid email
address. This is achieved by searching the value argument for the first occurrence of the regular
expression pattern specified in the Regex constructor. Whether the regular expression pattern has
been found in the input string can be determined by checking the value against Regex.IsMatch.
Note
41 CHAPTER 7 | Validation
Adding validation rules to a property
In the eShop multi-platform app, view model properties that require validation are declared to be of
type ValidatableObject<T>, where T is the type of the data to be validated. The following code
example shows an example of two such properties:
Password.Validations.Add(new IsNotNullOrEmptyRule<string>
{
ValidationMessage = "A password is required."
});
}
This method adds the IsNotNullOrEmptyRule<T> validation rule to the Validations collection of each
ValidatableObject<T> instance, specifying values for the validation rule’s ValidationMessage property,
which specifies the validation error message that will be displayed if validation fails.
Triggering validation
The validation approach used in the eShop multi-platform app can manually trigger validation of a
property, and automatically trigger validation when a property changes.
42 CHAPTER 7 | Validation
return _password.Validate();
}
The Validate method performs validation of the username and password entered by the user on the
LoginView, by invoking the Validate method on each ValidatableObject<T> instance. The following
code example shows the Validate method from the ValidatableObject<T> class:
IsValid = !Errors.Any();
return IsValid;
}
This method retrieves any validation rules that were added to the object’s Validations collection. The
Check method for each retrieved validation rule is executed, and the ValidationMessage property
value for any validation rule that fails to validate the data is added to the Errors collection of the
ValidatableObject<T> instance. Finally, the IsValid property is set, and its value is returned to the
calling method, indicating whether validation succeeded or failed.
The Entry control binds to the UserName.Value property of the ValidatableObject<T> instance, and
the control’s Behaviors collection has an EventToCommandBehavior instance added to it. This
behavior executes the ValidateUserNameCommand in response to the TextChanged event firing on
the Entry, which is raised when the text in the Entry changes. In turn, the ValidateUserNameCommand
delegate executes the ValidateUserName method, which executes the Validate method on the
ValidatableObject<T> instance. Therefore, every time the user enters a character in the Entry control
for the username, validation of the entered data is performed.
43 CHAPTER 7 | Validation
the user why the data is invalid below the control containing the invalid data. When the invalid data is
corrected, the background changes back to the default state and the error message is removed. The
image below shows the LoginView in the eShop multi-platform app when validation errors are
present.
44 CHAPTER 7 | Validation
Property Description
TargetType The control type that the trigger belongs to.
Binding The data Binding markup which will provide
change notifications and value for the trigger
condition.
Value The data value to specify when the trigger’s
condition has been met.
For this Entry, we will be listening for changes to the LoginViewModel.UserName.IsValid property.
Each time this property raises a change, the value will be compared against the Value property set in
the DataTrigger. If the values are equal, then the trigger condition will be met and any Setter objects
provided to the DataTrigger will be executed. This control has a single Setter object that updates the
BackgroundColor property to a custom color defined using the StaticResource markup. When a
Trigger condition is no longer met, the control will revert the properties set by the Setter object to
their previous state. For more information about Triggers, see .NET MAUI Docs: Triggers.
<Label
Each Label binds to the Errors property of the view model object that’s being validated. The Errors
property is provided by the ValidatableObject<T> class, and is of type IEnumerable<string>. Because
the Errors property can contain multiple validation errors, the FirstValidationErrorConverter instance is
used to retrieve the first error from the collection for display.
Summary
The eShop multi-platform app performs synchronous client-side validation of view model properties
and notifies the user of any validation errors by highlighting the control that contains the invalid data,
and by displaying error messages that inform the user why the data is invalid.
View model properties that require validation are of type ValidatableObject<T>, and each
ValidatableObject<T> instance has validation rules added to its Validations property. Validation is
invoked from the view model by calling the Validate method of the ValidatableObject<T> instance,
which retrieves the validation rules and executes them against the ValidatableObject<T> Value
property. Any validation errors are placed into the Errors property of the ValidatableObject<T>
instance, and the IsValid property of the ValidatableObject<T> instance is updated to indicate
whether validation succeeded or failed.
45 CHAPTER 7 | Validation
CHAPTER 8
Application settings
management
Settings allow the separation of data that configures the behavior of an app from the code, allowing
the behavior to be changed without rebuilding the app. There are two types of settings: app settings
and user settings.
App settings are data that an app creates and manages. It can include data such as fixed web service
endpoints, API keys, and runtime state. App settings are tied to core functionality and are only
meaningful to that app.
User settings are the customizable settings of an app that affect the app’s behavior and don’t require
frequent re-adjustment. For example, an app might let the user specify where to retrieve data and
how to display it on the screen.
namespace eShop.Services.Settings;
Adding Settings
.NET MAUI includes a preferences manager that provides a way to store runtime settings for a user.
This feature can be accessed from anywhere within your application using the
Microsoft.Maui.Storage.Preferences class. The preferences manager provides a consistent, type-safe,
cross-platform approach for persisting and retrieving app and user settings, while using the native
settings management provided by each platform. In addition, it’s straightforward to use data binding
to access settings data exposed by the library. For more information, see the Preferences on the
Microsoft Developer Center.
Tip
Preferences is meant for storing relatively small data. If you need to store larger or more complex
data, consider using a local database or filesystem to store the data.
Our application will use the Preferences class need to implement the ISettingsService interface. The
code below shows how the eShop multi-platform app’s SettingsService implements the
AuthTokenAccess and UseMocks properties:
Each setting consists of a private key, a private default value, and a public property. The key is always
a const string that defines a unique name, with the default value for the setting being a static read-
only or constant value of the required type. Providing a default value ensures that a valid value is
available if an unset setting is retrieved. This service implementation can be provided via dependency
injection to our application for use in view-models or other services throughout the application.
Data binding can be used to retrieve and set settings exposed by the ISettingService interface. This is
achieved by controls on the view binding to view model properties that in turn access properties in
the ISettingService interface and raising a property changed notification if the value has changed.
The following code example shows the Entry control from the SettingsView that allows the user to
enter a base identity endpoint URL for the containerized microservices:
This Entry control binds to the IdentityEndpoint property of the SettingsViewModel class, using a two-
way binding. The following code example shows the IdentityEndpoint property:
public SettingsViewModel(
ILocationService locationService, IAppEnvironmentService appEnvironmentService,
IDialogService dialogService, INavigationService navigationService, ISettingsService
settingsService)
: base(dialogService, navigationService, settingsService)
{
_settingsService = settingsService;
_identityEndpoint = _settingsService.IdentityEndpointBase;
}
if (!string.IsNullOrWhiteSpace(value))
{
UpdateIdentityEndpoint();
}
}
}
When the IdentityEndpoint property is set, the UpdateIdentityEndpoint method is called, provided
that the supplied value is valid. The following code example shows the UpdateIdentityEndpoint
method:
Summary
Settings allow the separation of data that configures the behavior of an app from the code, allowing
the behavior to be changed without rebuilding the app. App settings are data that an app creates and
manages, and user settings are the customizable settings of an app that affect the app’s behavior and
don’t require frequent re-adjustment.
Particularly concerning, in the age of the cloud, is that individual components can’t be easily scaled. A
monolithic application contains domain-specific functionality and is typically divided by functional
layers such as front-end, business logic, and data storage. The image below illustrates that a
monolithic application is scaled by cloning the entire application onto multiple machines.
Microservices can scale independently compared to giant monolithic applications that scale together.
This means that a specific functional area that requires more processing power or network bandwidth
to support demand can be scaled rather than unnecessarily scaling out other application areas. The
image below illustrates this approach, where microservices are deployed and scaled independently,
creating instances of services across machines.
The classic model for application scalability is to have a load-balanced, stateless tier with a shared
external datastore to store persistent data. Stateful microservices manage their own persistent data,
usually storing it locally on the servers on which they are placed, to avoid the overhead of network
access and complexity of cross-service operations. This enables the fastest possible processing of data
and can eliminate the need for caching systems. In addition, scalable stateful microservices usually
partition data among their instances, in order to manage data size and transfer throughput beyond
which a single server can support.
Microservices also support independent updates. This loose coupling between microservices provides
a rapid and reliable application evolution. Their independent, distributed nature helps rolling updates,
where only a subset of instances of a single microservice will update at any given time. Therefore, if a
problem is detected, a buggy update can be rolled back, before all instances update with the faulty
code or configuration. Similarly, microservices typically use schema versioning, so that clients see a
consistent version when updates are being applied, regardless of which microservice instance is being
communicated with.
Containerization
Containerization is an approach to software development in which an application and its versioned set
of dependencies, plus its environment configuration abstracted as deployment manifest files, are
packaged together as a container image, tested as a unit, and deployed to a host operating system.
There are many similarities between containers and virtual machines, as illustrated below.
The key concepts when creating and working with containers are:
Concept Description
Container Host The physical or virtual machine configured to
host containers. The container host will run one
or more containers.
Container Image An image consists of a union of layered
filesystems stacked on top of each other, and is
the basis of a container. An image does not
have state and it never changes as it’s deployed
to different environments.
Container A container is a runtime instance of an image.
The eShop reference application uses Docker to host four containerized back-end microservices, as
illustrated in the diagram below.
Each microservice has its own database, allowing it to be fully decoupled from the other
microservices. Where necessary, consistency between databases from different microservices is
achieved using application-level events. For more information, see Communication between
microservices.
Tip
Direct client-to-microservice communication can have drawbacks when building a large and complex
microservice-based application, but it’s more than adequate for a small application. Consider using
API gateway communication when designing a large microservice-based application with tens of
microservices.
The two common approaches for microservice-to-microservice communication are HTTP-based REST
communication when querying for data, and lightweight asynchronous messaging when
communicating updates across multiple microservices.
From an application perspective, the event bus is simply a publish-subscribe channel exposed via an
interface. However, the way the event bus is implemented can vary. For example, an event bus
implementation could use RabbitMQ, Azure Service Bus, or other service buses such as NServiceBus
and MassTransit. The diagram below shows how an event bus is used in the eShop reference
application.
The eShop event bus, implemented using RabbitMQ, provides one-to-many asynchronous publish-
subscribe functionality. This means that after publishing an event, there can be multiple subscribers
listening for the same event. The diagram below illustrates this relationship.
Summary
Microservices offer an approach to application development and deployment that’s suited to the
agility, scale, and reliability requirements of modern cloud applications. One of the main advantages
of microservices is that they can be scaled-out independently, which means that a specific functional
area can be scaled that requires more processing power or network bandwidth to support demand
without unnecessarily scaling areas of the application that are not experiencing increased demand.
Client apps should be able to utilize the web API without knowing how the data or operations that the
API exposes are implemented. This requires that the API abides by common standards that enable a
client app and web service to agree on which data formats to use, and the structure of the data that is
exchanged between client apps and the web service.
The REST model uses a navigational scheme to represent objects and services over a network, referred
to as resources. Systems that implement REST typically use the HTTP protocol to transmit requests to
access these resources. In such systems, a client app submits a request in the form of a URI that
identifies a resource, and an HTTP method (such as GET, POST, PUT, or DELETE) that indicates the
operation to be performed on that resource. The body of the HTTP request contains any data required
to perform the operation.
Note
REST defines a stateless request model. Therefore, HTTP requests must be independent and might
occur in any order.
The response from a REST request makes use of standard HTTP status codes. For example, a request
that returns valid data should include the HTTP response code 200 (OK), while a request that fails to
find or delete a specified resource should return a response that includes the HTTP status code 404
(Not Found).
A RESTful web API exposes a set of connected resources, and provides the core operations that
enable an app to manipulate those resources and easily navigate between them. For this reason, the
URIs that constitute a typical RESTful web API are oriented towards the data that it exposes, and use
the facilities provided by HTTP to operate on this data.
For more information about REST, see API design and API implementation on Microsoft Docs.
The image below shows the interaction of classes that read catalog data from the catalog microservice
for displaying by the CatalogView.
This method calls the GetCatalogAsync method of the CatalogService instance that was injected into
the CatalogViewModel by the dependency injection container. The following code example shows the
GetCatalogAsync method:
return catalog?.Data;
}
The following code example shows the GetAsync method in the RequestProvider class:
await HandleResponse(response);
TResult result = await response.Content.ReadFromJsonAsync<TResult>();
return result;
}
This method calls the GetOrCreateHttpClient method, which returns an instance of the HttpClient class
with the appropriate headers set. It then submits an asynchronous GET request to the resource
identified by the URI, with the response being stored in the HttpResponseMessage instance. The
HandleResponse method is then invoked, which throws an exception if the response doesn’t include a
success HTTP status code. Then the response is read as a string, converted from JSON to a
CatalogRoot object, and returned to the CatalogService.
if (!string.IsNullOrEmpty(token))
{
httpClient.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", token);
}
else
{
httpClient.DefaultRequestHeaders.Authorization = null;
}
This method uses creates a new instance or retrieves a cached instance of the HttpClient class, and
sets the Accept header of any requests made by the HttpClient instance to application/json, which
indicates that it expects the content of any response to be formatted using JSON. Then, if an access
token was passed as an argument to the GetOrCreateHttpClient method, it’s added to the
Authorization header of any requests made by the HttpClient instance, prefixed with the string Bearer.
For more information about authorization, see Authorization.
Tip
It is highly recommended to cache and reuse instances of the HttpClient for better application
performance. Creating a new HttpClient for each operation can lead to issue with socket exhaustion.
For more information, see HttpClient Instancing on the Microsoft Developer Center.
When the GetAsync method in the RequestProvider class calls HttpClient.GetAsync, the Items method
in the CatalogController class in the Catalog.API project is invoked, which is shown in the following
code example:
[HttpGet]
[Route("[action]")]
public async Task<IActionResult> Items(
[FromQuery]int pageSize = 10, [FromQuery]int pageIndex = 0)
{
var totalItems = await _catalogContext.CatalogItems
.LongCountAsync();
itemsOnPage = ComposePicUri(itemsOnPage);
var model = new PaginatedItemsViewModel<CatalogItem>(
pageIndex, pageSize, totalItems, itemsOnPage);
return Ok(model);
}
This method retrieves the catalog data from the SQL database using EntityFramework, and returns it
as a response message that includes a success HTTP status code, and a collection of JSON formatted
CatalogItem instances.
The image below shows the interaction of classes that send the basket data displayed by the
BasketView, to the basket microservice.
When an item is added to the shopping basket, the ReCalculateTotalAsync method in the
BasketViewModel class is called. This method updates the total value of items in the basket, and sends
the basket data to the basket microservice, as demonstrated in the following code example:
await _basketService.UpdateBasketAsync(
new CustomerBasket
{
BuyerId = userInfo.UserId,
Items = BasketItems.ToList()
},
authToken);
}
This method builds the URI that identifies the resource the request will be sent to, and uses the
RequestProvider class to invoke the POST HTTP method on the resource, before returning the results
to the BasketViewModel. Note that an access token, obtained from IdentityServer during the
authentication process, is required to authorize requests to the basket microservice. For more
information about authorization, see Authorization.
The following code example shows one of the PostAsync methods in the RequestProvider class:
await HandleResponse(response);
TResult result = await response.Content.ReadFromJsonAsync<TResult>();
return result;
}
This method calls the GetOrCreateHttpClient method, which returns an instance of the HttpClient class
with the appropriate headers set. It then submits an asynchronous POST request to the resource
identified by the URI, with the serialized basket data being sent in JSON format, and the response
being stored in the HttpResponseMessage instance. The HandleResponse method is then invoked,
which throws an exception if the response doesn’t include a success HTTP status code. Then, the
response is read as a string, converted from JSON to a CustomerBasket object, and returned to the
BasketService. For more information about the GetOrCreateHttpClient method, see Making a GET
request.
When the PostAsync method in the RequestProvider class calls HttpClient.PostAsync, the Post method
in the BasketController class in the Basket.API project is invoked, which is shown in the following code
example:
[HttpPost]
public async Task<IActionResult> Post([FromBody] CustomerBasket value)
{
var basket = await _repository.UpdateBasketAsync(value);
return Ok(basket);
}
When the checkout process is invoked, the CheckoutAsync method in the CheckoutViewModel class is
called. This method creates a new order, before clearing the shopping basket, as demonstrated in the
following code example:
await _basketService.ClearBasketAsync(
_shippingAddress.Id.ToString(), authToken);
}
This method calls the ClearBasketAsync method of the BasketService instance that was injected into
the CheckoutViewModel by the dependency injection container. The following method shows the
ClearBasketAsync method:
The following code example shows the DeleteAsync method in the RequestProvider class:
This method calls the GetOrCreateHttpClient method, which returns an instance of the HttpClient class
with the appropriate headers set. It then submits an asynchronous DELETE request to the resource
identified by the URI. For more information about the GetOrCreateHttpClient method, see Making a
GET request.
When the DeleteAsync method in the RequestProvider class calls HttpClient.DeleteAsync, the Delete
method in the BasketController class in the Basket.API project is invoked, which is shown in the
following code example:
[HttpDelete("{id}")]
public void Delete(string id) =>
_repository.DeleteBasketAsync(id);
This method uses an instance of the RedisBasketRepository class to delete the basket data from the
Redis cache.
Caching data
The performance of an app can be improved by caching frequently accessed data to fast storage
that’s located close to the app. If the fast storage is located closer to the app than the original source,
then caching can significantly improve response times when retrieving data.
The most common form of caching is read-through caching, where an app retrieves data by
referencing the cache. If the data isn’t in the cache, it’s retrieved from the data store and added to the
cache. Apps can implement read-through caching with the cache-aside pattern. This pattern
determines whether the item is currently in the cache. If the item isn’t in the cache, it’s read from the
data store and added to the cache. For more information, see the Cache-Aside pattern on Microsoft
Docs.
Tip
This data can be added to the cache on demand the first time it is retrieved by an app. This means
that the app needs to fetch the data only once from the data store, and that subsequent access can
be satisfied by using the cache.
Tip
Think of the cache as a transient data store that could disappear at any time.
Ensure that data is maintained in the original data store as well as the cache. The chances of losing
data are then minimized if the cache becomes unavailable.
Tip
Many caches implement expiration, which invalidates data and removes it from the cache if it’s not
accessed for a specified period. However, care must be taken when choosing the expiration period. If
it’s made too short, data will expire too quickly and the benefits of caching will be reduced. If it’s
made too long, the data risks becoming stale. Therefore, the expiration time should match the pattern
of access for apps that use the data.
When cached data expires, it should be removed from the cache, and the app must retrieve the data
from the original data store and place it back into the cache.
It’s also possible that a cache might fill up if data is allowed to remain for too long a period. Therefore,
requests to add new items to the cache might be required to remove some items in a process known
as eviction. Caching services typically evict data on a least-recently-used basis. However, there are
other eviction policies, including most-recently-used, and first-in-first-out. For more information, see
Caching Guidance on Microsoft Docs.
Caching images
The eShop multi-platform app consumes remote product images that benefit from being cached.
These images are displayed by the Image control. The .NET MAUI Image control supports caching of
Increasing resilience
All apps that communicate with remote services and resources must be sensitive to transient faults.
Transient faults include the momentary loss of network connectivity to services, the temporary
unavailability of a service, or timeouts that arise when a service is busy. These faults are often self-
correcting, and if the action is repeated after a suitable delay it’s likely to succeed.
Transient faults can have a huge impact on the perceived quality of an app, even if it has been
thoroughly tested under all foreseeable circumstances. To ensure that an app that communicates with
remote services operates reliably, it must be able to do all of the following:
• Detect faults when they occur, and determine if the faults are likely to be transient.
• Retry the operation if it determines that the fault is likely to be transient and keep track of the
number of times the operation was retried.
• Use an appropriate retry strategy, which specifies the number of retries, the delay between
each attempt, and the actions to take after a failed attempt.
This transient fault handling can be achieved by wrapping all attempts to access a remote service in
code that implements the retry pattern.
Retry pattern
If an app detects a failure when it tries to send a request to a remote service, it can handle the failure
in any of the following ways:
• Retrying the operation. The app could retry the failing request immediately.
• Retrying the operation after a delay. The app should wait for a suitable amount of time before
retrying the request.
• Cancelling the operation. The application should cancel the operation and report an
exception.
The retry strategy should be tuned to match the business requirements of the app. For example, it’s
important to optimize the retry count and retry interval to the operation being attempted. If the
operation is part of a user interaction, the retry interval should be short and only a few retries
attempted to avoid making users wait for a response. If the operation is part of a long running
workflow, where cancelling or restarting the workflow is expensive or time-consuming, it’s appropriate
to wait longer between attempts and to retry more times.
Note
An aggressive retry strategy with minimal delay between attempts, and a large number of retries,
could degrade a remote service that’s running close to or at capacity. In addition, such a retry strategy
could also affect the responsiveness of the app if it’s continually trying to perform a failing operation.
Tip
Use a finite number of retries, or implement the Circuit Breaker pattern to allow a service to recover.
For more information about the retry pattern, see the Retry pattern on Microsoft Docs.
The circuit breaker pattern can prevent an app from repeatedly trying to execute an operation that’s
likely to fail, while also enabling the app to detect whether the fault has been resolved.
Note
The purpose of the circuit breaker pattern is different from the retry pattern. The retry pattern enables
an app to retry an operation in the expectation that it’ll succeed. The circuit breaker pattern prevents
an app from performing an operation that’s likely to fail.
A circuit breaker acts as a proxy for operations that might fail. The proxy should monitor the number
of recent failures that have occurred, and use this information to decide whether to allow the
operation to proceed, or to return an exception immediately.
The eShop multi-platform app does not currently implement the circuit breaker pattern. However, the
eShop does.
Tip
An app can combine the retry and circuit breaker patterns by using the retry pattern to invoke an
operation through a circuit breaker. However, the retry logic should be sensitive to any exceptions
returned by the circuit breaker and abandon retry attempts if the circuit breaker indicates that a fault
is not transient.
For more information about the circuit breaker pattern, see the Circuit Breaker pattern on Microsoft
Docs.
The performance of an app can be improved by caching frequently accessed data to fast storage
that’s located close to the app. Apps can implement read-through caching with the cache-aside
pattern. This pattern determines whether the item is currently in the cache. If the item isn’t in the
cache, it’s read from the data store and added to the cache.
When communicating with web APIs, apps must be sensitive to transient faults. Transient faults
include the momentary loss of network connectivity to services, the temporary unavailability of a
service, or timeouts that arise when a service is busy. These faults are often self-correcting, and if the
action is repeated after a suitable delay, then it’s likely to succeed. Therefore, apps should wrap all
attempts to access a web API in code that implements a transient fault handling mechanism.
There are many approaches to integrating authentication and authorization into a .NET MAUI app that
communicates with an ASP.NET web application, including using ASP.NET Core Identity, external
authentication providers such as Microsoft, Google, Facebook, or Twitter, and authentication
middleware. The eShop multi-platform app performs authentication and authorization with a
containerized identity microservice that uses IdentityServer. The app requests security tokens from
IdentityServer to authenticate a user or access a resource. For IdentityServer to issue tokens on behalf
of a user, the user must sign in to IdentityServer. However, IdentityServer doesn’t provide a user
interface or database for authentication. Therefore, in the eShop reference application, ASP.NET Core
Identity is used for this purpose.
Authentication
Authentication is required when an application needs to know the current user’s identity. ASP.NET
Core’s primary mechanism for identifying users is the ASP.NET Core Identity membership system,
which stores user information in a data store configured by the developer. Typically, this data store
will be an EntityFramework store, though custom stores or third-party packages can be used to store
identity information in Azure storage, DocumentDB, or other locations.
For authentication scenarios that use a local user datastore and persist identity information between
requests via cookies (as is typical in ASP.NET web applications), ASP.NET Core Identity is a suitable
solution. However, cookies are not always a natural means of persisting and transmitting data. For
example, an ASP.NET Core web application that exposes RESTful endpoints that are accessed from an
app will typically need to use bearer token authentication since cookies can’t be used in this scenario.
However, bearer tokens can easily be retrieved and included in the authorization header of web
requests made from the app.
Note
OpenID Connect and OAuth 2.0 are very similar, while having different responsibilities.
OpenID Connect is an authentication layer on top of the OAuth 2.0 protocol. OAuth 2 is a protocol
that allows applications to request access tokens from a security token service and use them to
communicate with APIs. This delegation reduces complexity in both client applications and APIs since
authentication and authorization can be centralized.
OpenID Connect and OAuth 2.0 combine the two fundamental security concerns of authentication
and API access, and IdentityServer is an implementation of these protocols.
In applications that use direct client-to-microservice communication, such as the eShop reference
application, a dedicated authentication microservice acting as a Security Token Service (STS) can be
used to authenticate users, as shown in the following diagram. For more information about direct
client-to-microservice communication, see Microservices.
The eShop multi-platform app communicates with the identity microservice, which uses IdentityServer
to perform authentication, and access control for APIs. Therefore, the multi-platform app requests
tokens from IdentityServer, either for authenticating a user or for accessing a resource:
Note
A client must be registered with IdentityServer before it can successfully request tokens. For more
information on adding clients, see Defining Clients.
...
app.UseIdentityServer();
Order matters in the web application’s HTTP request processing pipeline. Therefore, IdentityServer
must be added to the pipeline before the UI framework that implements the login screen.
Configuring IdentityServer
IdentityServer should be configured in the ConfigureServices method in the web application’s Startup
class by calling the services.AddIdentityServer method, as demonstrated in the following code
example from the eShop reference application:
After calling the services.AddIdentityServer method, additional fluent APIs are called to configure the
following:
Tip
Dynamically load the IdentityServer configuration. IdentityServer’s APIs allow for configuring
IdentityServer from an in-memory list of configuration objects. In the eShop reference application,
these in-memory collections are hard-coded into the application. However, in production scenarios
they can be loaded dynamically from a configuration file or from a database.
This method specifies that IdentityServer should protect the orders and basket APIs. Therefore,
IdentityServer-managed access tokens will be required when making calls to these APIs. For more
information about the ApiResource type, see API Resource in the IdentityServer documentation.
The OpenID Connect specification specifies some standard identity resources. The minimum
requirement is that support is provided for emitting a unique ID for users. This is achieved by
exposing the IdentityResources.OpenId identity resource.
Note
The IdentityResources class supports all of the scopes defined in the OpenID Connect specification
(openid, email, profile, telephone, and address).
IdentityServer also supports defining custom identity resources. For more information, see Defining
custom identity resources in the IdentityServer documentation. For more information about the
IdentityResource type, see Identity Resource in the IdentityServer documentation.
Property Description
ClientId A unique ID for the client.
ClientName The client display name, which is used for
logging and the consent screen.
Tip
Consider using the hybrid authentication flow. The hybrid authentication flow mitigates a number of
attacks that apply to the browser channel, and is the recommended flow for native applications that
want to retrieve access tokens (and possibly refresh tokens).
For more information about authentication flows, see Grant Types in the IdentityServer
documentation.
Performing authentication
For IdentityServer to issue tokens on behalf of a user, the user must sign in to IdentityServer. However,
IdentityServer doesn’t provide a user interface or database for authentication. Therefore, in the eShop
reference application, ASP.NET Core Identity is used for this purpose.
The eShop multi-platform app authenticates with IdentityServer with the hybrid authentication flow,
which is illustrated in the diagram below.
The eShop multi-platform app signs out of IdentityServer by sending a request to <base
endpoint>:5105/connect/endsession with additional parameters. After sign-out, IdentityServer
responds by sending a post-logout redirecting URI back to the multi-platform app. The diagram
below illustrates this process.
Signing-in
When the user taps the LOGIN button on the LoginView, the SignInCommand in the LoginViewModel
class is executed, which in turn executes the SignInAsync method. The following code example shows
this method:
[RelayCommand]
private async Task SignInAsync()
{
await IsBusyFor(
async () =>
{
var loginSuccess = await _appEnvironmentService.IdentityService.SignInAsync();
if (loginSuccess)
{
await NavigationService.NavigateToAsync("//Main/Catalog");
}
This method invokes the SignInAsync method in the IdentityService class, as shown in the following
code example:
if (response.IsError)
{
return false;
}
await _settingsService
.SetUserTokenAsync(
new UserToken
{
AccessToken = response.AccessToken,
IdToken = response.IdentityToken,
RefreshToken = response.RefreshToken,
ExpiresAt = response.AccessTokenExpiration
})
.ConfigureAwait(false);
return !response.IsError;
}
The IdentityService makes use of the OidcClient provided with the IdentityModel.OidcClient NuGet
package. This client displays the authentication web view to the user in the application and captures
the authentication result. The client connects to the URI for IdentityServer’s authorization endpoint
with the required parameters. The authorization endpoint is at /connect/authorize on port 5105 of the
base endpoint exposed as a user setting. For more information about user settings, see Configuration
Management.
Note
The attack surface of the eShop multi-platform app is reduced by implementing the Proof Key for
Code Exchange (PKCE) extension to OAuth. PKCE protects the authorization code from being used if
it’s intercepted. This is achieved by the client generating a secret verifier, a hash of which is passed in
the authorization request, and which is presented unhashed when redeeming the authorization code.
For more information about PKCE, see Proof Key for Code Exchange by OAuth Public Clients on the
Internet Engineering Task Force web site.
Note
The eShop also allows a mock sign in when the app is configured to use mock services in the
SettingsView. In this mode, the app doesn’t communicate with IdentityServer, instead allowing the
user to sign in using any credentials.
Signing-out
When the user taps the LOG OUT button in the ProfileView, the LogoutCommand in the
ProfileViewModel class is executed, which executes the LogoutAsync method. This method performs
page navigation to the LoginView page, passing a Logout query parameter set to true.
That parameter is evaluated in the ApplyQueryAttributes method. If the Logout parameter is present
with a true value, the PerformLogoutAsync method of the LoginViewModel class is executed, which is
shown in the following code example:
_settingsService.UseFakeLocation = false;
UserName.Value = string.Empty;
Password.Value = string.Empty;
}
This method invokes the SignOutAsync method in the IdentityService class, which invokes the
OidcClient to end the user’s session and clears any saved user tokens. For more information about
application settings, see Configuration management. The following code example shows the
SignOutAsync method:
if (response.IsError)
{
return false;
}
await _settingsService.SetUserTokenAsync(default);
return !response.IsError;
}
This method uses the OidcClient to call the URI to IdentityServer’s end session endpoint with the
required parameters. The end session endpoint is at /connect/endsession on port 5105 of the base
endpoint exposed as a user setting. Once the user has successfully signed out, LoginView is presented
to the user, and any saved user information will be cleared.
Note
The eShop also allows a mock sign-out when the app is configured to use mock services in the
SettingsView. In this mode, the app doesn’t communicate with IdentityServer, and instead clears any
stored tokens from application settings.
Authorization
After authentication, ASP.NET Core web APIs often need to authorize access, which allows a service to
make APIs available to some authenticated users but not to all.
Restricting access to an ASP.NET Core route can be achieved by applying an Authorize attribute to a
controller or action, which limits access to the controller or action to authenticated users, as shown in
the following code example:
[Authorize]
public sealed class BasketController : Controller
{
// Omitted for brevity
}
If an unauthorized user attempts to access a controller or action marked with the Authorize attribute,
the API framework returns a 401 (unauthorized) HTTP status code.
Note
Parameters can be specified on the Authorize attribute to restrict an API to specific users. For more
information, see ASP.NET Core Docs: Authorization.
IdentityServer can be integrated into the authorization workflow so that the access tokens provide
control authorization. This approach is shown in the diagram below.
if (!identitySection.Exists())
{
// No identity section, so no authentication
return services;
}
services.AddAuthentication().AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.Audience = audience;
options.TokenValidationParameters.ValidIssuers = [identityUrl];
options.TokenValidationParameters.ValidateAudience = false;
});
services.AddAuthorization();
return services;
}
This method ensures that the API can only be accessed with a valid access token. The middleware
validates the incoming token to ensure that it’s sent from a trusted issuer and validates that the token
is valid to be used with the API that receives it. Therefore, browsing to the ordering or basket
controller will return a 401 (unauthorized) HTTP status code, indicating that an access token is
required.
if (string.IsNullOrEmpty(authToken))
{
return;
}
The access token is stored with the IIdentityService implementation and can be retrieved using the
GetAuthTokenAsync method.
Similarly, the access token must be included when sending data to an IdentityServer protected API, as
shown in the following code example:
if (string.IsNullOrEmpty(authToken))
{
return;
The access token is retrieved from the IIdentityService and included in the call to the ClearBasketAsync
method in the BasketService class.
The RequestProvider class in the eShop multi-platform app uses the HttpClient class to make requests
to the RESTful APIs exposed by the eShop reference application. When making requests to the
ordering and basket APIs, which require authorization, a valid access token must be included with the
request. This is achieved by adding the access token to the headers of the HttpClient instance, as
demonstrated in the following code example:
The DefaultRequestHeaders property of the HttpClient class exposes the headers that are sent with
each request, and the access token is added to the Authorization header prefixed with the string
Bearer. When the request is sent to a RESTful API, the value of the Authorization header is extracted
and validated to ensure that it’s sent from a trusted issuer and used to determine whether the user
has permission to invoke the API that receives it.
For more information about how the eShop multi-platform app makes web requests, see Accessing
remote data.
Summary
There are many approaches to integrating authentication and authorization into a .NET MAUI app that
communicates with an ASP.NET web application. The eShop multi-platform app performs
authentication and authorization with a containerized identity microservice that uses IdentityServer.
IdentityServer is an open-source OpenID Connect and OAuth 2.0 framework for ASP.NET Core that
integrates with ASP.NET Core Identity to perform bearer token authentication.
The multi-platform app requests security tokens from IdentityServer to authenticate a user or access a
resource. When accessing a resource, an access token must be included in the request to APIs that
require authorization. IdentityServer’s middleware validates incoming access tokens to ensure that
they are sent from a trusted issuer and that they are valid to be used with the API that receives them.
storageField = newValue;
RaisePropertyChanged(propertyName);
}
The CommunityToolkit.Mvvm NuGet Package (aka MVVM Toolkit) can be used to help address and
simplify these common MVVM patterns. The MVVM Toolkit, along with newer features to the .NET
language, allows for simplified logic, easy adoption into a project, and runtime independence. The
example below shows the same ViewModel using components that come with the MVVM Toolkit:
[ObservableProperty]
private int _value;
}
Note
The MVVM Toolkit is provided with the CommunityToolkit.Mvvm package. For information on how to
add the package to your project, see Introduction to the MVVM Toolkit on the Microsoft Developer
Center.
In comparison to the original example, we were able to drastically reduce the overall complexity and
simplify the maintainability of our ViewModel. The MVVM Toolkit comes with many pre-built common
components and features, such as the ObservableObject shown above, that simplifies and
standardizes the code that we have throughout the application.
ObservableObject
The MVVM Toolkit provides ObservableObject which is intended for use as the base of our
ViewModel objects or any object that needs to raise change notifications. It implements
INotifyPropertyChanged and INotifyPropertyChanging along with helper methods for setting
properties and raising changes. Below is an example of a standard ViewModel using
ObservableObject:
ObservableObject handles all of the logic needed for raising change notifications by using the
SetProperty method in your property setter. If you have a property that returns a Task<T>, the
SetPropertyAndNotifyOnCompletion method can be used to delay publishing a property change until
the task has been completed. The methods OnPropertyChanged and OnPropertyChanging that can
also be used for raising property changes where needed in your object.
For more detailed information on ObservableObject, see ObservableObject in the MVVM Toolkit
Developer Center.
The MVVM Toolkit comes with two commands, RelayCommand and AsyncRelayCommand.
RelayCommand is intended for situations where you have synchronous code to execute and has a
fairly similar implementation to the .NET MAUI Command object.
Note
Even though the .NET MAUI Command and RelayCommand are similar, using RelayCommand allows
for decoupling your ViewModel from any direct .NET MAUI references. This means that your
ViewModel is more portable, leading to easier reuse across projects.
AsyncRelayCommand provides many additional features when working with asynchronous workflows.
This is quite common in our ViewModel as we are typically communicating with repositories, APIs,
databases, and other systems that utilize async/await. The AsyncRelayCommand constructor takes in
an execution task defined as a Func<Task> or a delegate returning Task as part of the constructor.
While the execution task is running, AsyncRelayCommand will monitor the state of the task and
provides updates using the IsRunning property. The IsRunning property can be bound to the UI which
helps manage control states such as showing loading with an ActivityIndicator or disabling/enabling a
control. While the execution task is being executed, the Cancel method can be called to attempt
cancellation of the execution task, if supported.
By default, AsyncRelayCommand doesn’t allow concurrent execution. This is very helpful in situations
where a user could unintentionally tap a control multiple times to execute a long-running or costly
operation. During task execution, AsyncRelayCommand will automatically call the CanExecuteChanged
event. In .NET MAUI, controls that support the Command and CommandParameter properties, such as
Button, will listen to this event and automatically enable or disable it during execution. This
functionality can be overridden by using a custom canExecute parameter or setting the
AsyncRelayCommandOptions.AllowConcurrentExecutions flag in the constructor.
Source Generators
Using the MVVM Toolkit components out-of-the-box allows you to greatly simplify our ViewModel.
The MVVM Toolkit allows you to simplify common code use cases even further by using Source
Generators. The MVVM Toolkit source generators look for specific attributes in our code and can
generate wrappers for properties and commands.
Important
The MVVM Toolkit Source Generators generate code that is additive to our existing objects. Because
of this, any object that is leveraging a source generator will need to be marked as partial.
The MVVM Toolkit ObservableProperty attribute can be applied to fields in objects that inherit from
ObservableObject and will wrap a private field with a property that generates changes. The following
code shows an example of using the ObservableObject attribute on the _name field:
With the ObservableProperty attribute applied to the _name field, the source generator will run and
generate another partial class with the following code:
The generated SampleViewModel has used the private _name field and generated a new Name
property that implements all of the logic needed for raising change notifications.
[ObservableProperty]
private string _name;
[ObservableProperty]
bool _isValid;
[RelayCommand]
private Task SettingsAsync()
{
return NavigationService.NavigateToAsync("Settings");
}
[RelayCommand]
private void Validate()
{
IsValid = !string.IsNullOrEmpty(Name);
}
}
The RelayCommand applied to the Validate method will generate a RelayCommand validate
ValidateCommand because it has a void return and the SettingsAsync method will generate an
AsyncRelayCommand named SettingsCommand. The source generator will generate the following
code in other partial classes:
All of the complexity of wrapping our ViewModel’s methods with an ICommand implementation has
been handled by the source generator.
For more detailed information on MVVM Toolkit Source Generators, see MVVM source generators in
the MVVM Toolkit Developer Center.
A unit test takes a small unit of the app, typically a method, isolates it from the remainder of the code,
and verifies that it behaves as expected. Its goal is to check that each unit of functionality performs as
expected, so errors don’t propagate throughout the app. Detecting a bug where it occurs is more
efficient that observing the effect of a bug indirectly at a secondary point of failure.
Unit testing has the most significant effect on code quality when it’s an integral part of the software
development workflow. Unit tests can act as design documentation and functional specifications for
an application. As soon as a method has been written, unit tests should be written that verify the
method’s behavior in response to standard, boundary, and incorrect input data cases and check any
explicit or implicit assumptions made by the code. Alternatively, with test-driven development, unit
tests are written before the code. For more information on test-driven development and how to
implement it, see Walkthrough: Test-driven development using Test Explorer.
Note
Unit tests are very effective against regression. That is, functionality that used to work, but has been
disturbed by a faulty update.
Step Description
Arrange Initializes objects and sets the value of the data
that is passed to the method under test.
Act Invokes the method under test with the required
arguments.
Assert Verifies that the action of the method under test
behaves as expected.
This pattern ensures that unit tests are readable, self-describing, and consistent.
public OrderDetailViewModel(
IAppEnvironmentService appEnvironmentService,
IDialogService dialogService, INavigationService navigationService,
ISettingsService settingsService)
: base(dialogService, navigationService, settingsService)
{
_appEnvironmentService = appEnvironmentService;
}
}
The OrderDetailViewModel class has a dependency on the IAppEnvironmentService type, which the
dependency injection container resolves when it instantiates an OrderDetailViewModel object.
However, rather than create an IAppEnvironmentService object which utilizes real servers, devices and
configurations to unit test the OrderDetailViewModel class, instead, replace the
IAppEnvironmentService object with a mock object for the purpose of the tests. A mock object is one
that has the same signature of an object or an interface, but is created in a specific manner to help
with unit testing. It is often used with dependency injection to provide specific implementations of
interfaces for testing different data and workflow scenarios.
This approach allows the IAppEnvironmentService object to be passed into the OrderDetailViewModel
class at runtime, and in the interests of testability, it allows a mock class to be passed into the
OrderDetailViewModel class at test time. The main advantage of this approach is that it enables unit
tests to be executed without requiring unwieldy resources such as runtime platform features, web
services, or databases.
Tip
Test one thing with each unit test. As the complexity of a test expands, it makes verification of that
test more difficult. By limiting a unit test to a single concern, we can ensure that our tests are more
repeatable, isolated, and have a smaller execution time. See
Unit testing best practices with .NET for more best practices.
The eShop multi-platform app uses MSTest to perform unit testing, which supports two different
types of unit tests:
The unit tests included with the eShop multi-platform app are TestMethod, so each unit test method
is decorated with the TestMethod attribute. In addition to MSTest there are several other testing
frameworks available including NUnit and xUnit.
[TestMethod]
public async Task OrderPropertyIsNotNullAfterViewModelInitializationTest()
{
// Arrange
var orderService = new OrderMockService();
var orderViewModel = new OrderDetailViewModel(orderService);
// Act
var order = await orderService.GetOrderAsync(1, GlobalSetting.Instance.AuthToken);
await orderViewModel.InitializeAsync(order);
// Assert
Assert.IsNotNull(orderViewModel.Order);
}
This unit test checks that the Order property of the OrderDetailViewModel instance will have a value
after the InitializeAsync method has been invoked. The InitializeAsync method is invoked when the
view model’s corresponding view is navigated to. For more information about navigation, see
Navigation.
Properties that can be updated directly by the unit test can be tested by attaching an event handler to
the PropertyChanged event and checking whether the event is raised after setting a new value for the
property. The following code example shows such a test:
[TestMethod]
public async Task SettingOrderPropertyShouldRaisePropertyChanged()
{
var invoked = false;
var orderService = new OrderMockService();
var orderViewModel = new OrderDetailViewModel(orderService);
Assert.IsTrue(invoked);
}
This unit test invokes the InitializeAsync method of the OrderViewModel class, which causes its Order
property to be updated. The unit test will pass, provided that the PropertyChanged event is raised for
the Order property.
[TestMethod]
public void AddCatalogItemCommandSendsAddProductMessageTest()
{
var messageReceived = false;
var catalogService = new CatalogMockService();
var catalogViewModel = new CatalogViewModel(catalogService);
MessagingCenter.Subscribe<CatalogViewModel, CatalogItem>(
this, MessageKeys.AddProduct, (sender, arg) =>
{
messageReceived = true;
});
catalogViewModel.AddCatalogItemCommand.Execute(null);
This unit test checks that the CatalogViewModel publishes the AddProduct message in response to its
AddCatalogItemCommand being executed. Because the MessagingCenter class supports multicast
message subscriptions, the unit test can subscribe to the AddProduct message and execute a callback
delegate in response to receiving it. This callback delegate, specified as a lambda expression, sets a
boolean field that’s used by the Assert statement to verify the behavior of the test.
[TestMethod]
public void InvalidEventNameShouldThrowArgumentExceptionText()
{
var behavior = new MockEventToCommandBehavior
{
EventName = "OnItemTapped"
};
var listView = new ListView();
This unit test will throw an exception because the ListView control does not have an event named
OnItemTapped. The Assert.Throws<T> method is a generic method where T is the type of the
expected exception. The argument passed to the Assert.Throws<T> method is a lambda expression
that will throw the exception. Therefore, the unit test will pass provided that the lambda expression
throws an ArgumentException.
Tip
Avoid writing unit tests that examine exception message strings. Exception message strings might
change over time, and so unit tests that rely on their presence are regarded as brittle.
Testing validation
There are two aspects to testing the validation implementation: testing that any validation rules are
correctly implemented and testing that the ValidatableObject<T> class performs as expected.
Validation logic is usually simple to test, because it is typically a self-contained process where the
output depends on the input. There should be tests on the results of invoking the Validate method on
each property that has at least one associated validation rule, as demonstrated in the following code
example:
[TestMethod]
public void CheckValidationPassesWhenBothPropertiesHaveDataTest()
{
Assert.IsTrue(isValid);
}
This unit test checks that validation succeeds when the two ValidatableObject<T> properties in the
MockViewModel instance both have data.
As well as checking that validation succeeds, validation unit tests should also check the values of the
Value, IsValid, and Errors property of each ValidatableObject<T> instance, to verify that the class
performs as expected. The following code example demonstrates a unit test that does this:
[TestMethod]
public void CheckValidationFailsWhenOnlyForenameHasDataTest()
{
var mockViewModel = new MockViewModel();
mockViewModel.Forename.Value = "John";
Assert.IsFalse(isValid);
Assert.IsNotNull(mockViewModel.Forename.Value);
Assert.IsNull(mockViewModel.Surname.Value);
Assert.IsTrue(mockViewModel.Forename.IsValid);
Assert.IsFalse(mockViewModel.Surname.IsValid);
Assert.AreEqual(mockViewModel.Forename.Errors.Count(), 0);
Assert.AreNotEqual(mockViewModel.Surname.Errors.Count(), 0);
}
This unit test checks that validation fails when the Surname property of the MockViewModel doesn’t
have any data, and the Value, IsValid, and Errors property of each ValidatableObject<T> instance are
correctly set.
Summary
A unit test takes a small unit of the app, typically a method, isolates it from the remainder of the code,
and verifies that it behaves as expected. Its goal is to check that each unit of functionality performs as
expected, so errors don’t propagate throughout the app.
The behavior of an object under test can be isolated by replacing dependent objects with mock
objects that simulate the behavior of the dependent objects. This enables unit tests to be executed
without requiring unwieldy resources such as runtime platform features, web services, or databases
Testing models and view models from MVVM applications is identical to testing any other classes, and
the same tools and techniques can be used.