Dependency injection (DI) supplies an object’s collaborators from outside instead of having the object construct them itself. In a .NET MAUI app, the built-in DI container is part of the generic host builder. Register pages, ViewModels, services, and other dependencies there; the container can then create objects with their required implementations. section 8.0 section 8.2
Constructor injection makes requirements visible. Rather than creating an AuthService inside LoginPage, accept IAuthService in the page constructor. AuthService can likewise accept IBrowser in its constructor. The container resolves the registered implementation and assembles the object graph, while consumers depend on interfaces rather than specific implementations. section 8.2.2 section 9.7
Choose registrations around the lifetime an app needs:
- Register pages and ViewModels as transient when each navigation or use should receive a clean instance. section 8.2
- Register services as singleton when one instance should last for the running app, such as API or database-facing services that may hold app-wide state. section 8.2
- Treat Shell pages differently when appropriate: pages added through Shell are automatically singleton, supporting fast return navigation to the same page instance. section 8.2
Inject a ViewModel into a page
A page can receive InputViewModel through its constructor, save it in a field, assign its Navigation property, and set it as BindingContext. Because the page no longer has a parameterless constructor, register both the page and its ViewModel so DI can resolve them during navigation. section 9.5.3 section 10.3.1
DI also configures HTTP clients. Register named HttpClient instances with AddHttpClient and attach focused delegating handlers, such as one that adds an access token. A service injects IHttpClientFactory and calls CreateClient with the required name. Keep request modifications in separate handlers rather than combining unrelated work in one handler. section 8.3.3
Table 8.2 Scope lifetimes for different dependencies in a .NET MAUI app (view table figure)
Compare transient pages and ViewModels with singleton services, including the UX and state-management reasons for each lifetime. section 8.2
Avoid solving missing constructor dependencies by exposing the service collection globally and resolving services from anywhere. That approach is identified as the service locator antipattern. Prefer registering dependencies and passing them through constructors; persist state in appropriate services rather than reusing page instances to retain it. section 8.2 section 8.2.2




















