Skip to content

Commit cebf932

Browse files
committed
refactor: Update performance and security guidelines in MAUI documentation
1 parent c8b59eb commit cebf932

File tree

2 files changed

+63
-24
lines changed

2 files changed

+63
-24
lines changed

agents/dotnet-maui.agent.md

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,7 @@ await Shell.Current.GoToAsync("details?id=123");
137137

138138
### Performance
139139
1. Use compiled bindings (`x:DataType`)
140-
2. Enable `<TrimMode>full</TrimMode>`
141-
3. Enable `<PublishAot>true</PublishAot>` (.NET 9+)
142-
4. Profile release builds only
143-
5. Lazy load resources
144-
6. Unsubscribe events, dispose resources
145-
7. Use Grid > StackLayout, CollectionView > ListView, Border > Frame
140+
2. Use Grid > StackLayout, CollectionView > ListView, Border > Frame
146141

147142
### Security
148143
```csharp

instructions/dotnet-maui.instructions.md

Lines changed: 62 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ applyTo: '**/*.xaml, **/*.cs'
99

1010
- Write idiomatic and efficient .NET MAUI and C# code.
1111
- Follow .NET and .NET MAUI conventions.
12-
- Prefer inline functions for smaller components but separate complex logic into code-behind or service classes.
13-
- Async/await should be used where applicable to ensure non-blocking UI operations.
12+
- Keep UI (Views) focused on layout and bindings; keep logic in ViewModels and services.
13+
- Use async/await for I/O and long-running work to keep the UI responsive.
1414

1515
## Naming Conventions
1616

@@ -21,38 +21,79 @@ applyTo: '**/*.xaml, **/*.cs'
2121
## .NET MAUI and .NET Specific Guidelines
2222

2323
- Utilize .NET MAUI's built-in features for component lifecycle (e.g. OnAppearing, OnDisappearing).
24-
- Use data binding effectively with {Binding}.
24+
- Use data binding effectively with `{Binding}` and MVVM patterns.
2525
- Structure .NET MAUI components and services following Separation of Concerns.
26-
- Always use the latest version C#, currently C# 13 features like record types, pattern matching, and global usings.
26+
- Use the language version supported by the repo's target .NET SDK and settings; avoid requiring preview language features unless the project is already configured for them.
27+
28+
## Critical Rules (Consistency)
29+
30+
- NEVER use ListView (deprecated). Use CollectionView.
31+
- NEVER use TableView (deprecated). Prefer CollectionView or layouts such as Grid/VerticalStackLayout.
32+
- NEVER use Frame (deprecated). Use Border instead.
33+
- NEVER use `*AndExpand` layout options (deprecated). Use Grid and explicit sizing instead.
34+
- NEVER place ScrollView or CollectionView inside StackLayout/VerticalStackLayout/HorizontalStackLayout (can break scrolling and virtualization). Use Grid as the parent layout.
35+
- NEVER reference images as `.svg` at runtime. Use PNG/JPG resources.
36+
- NEVER mix Shell navigation with NavigationPage/TabbedPage/FlyoutPage.
37+
- NEVER use renderers. Use handlers.
38+
- NEVER set `BackgroundColor`; use `Background` (supports gradients/brushes and is the preferred modern API).
39+
40+
## Layout and Control Selection
41+
42+
- Prefer `VerticalStackLayout`/`HorizontalStackLayout` over `StackLayout Orientation="..."` (more performant).
43+
- Use `BindableLayout` for small, non-scrollable lists (≤20 items). Use `CollectionView` for larger or scrollable lists.
44+
- Prefer `Grid` for complex layouts and when you need to subdivide space.
45+
- Prefer `Border` over `Frame` for containers with borders/backgrounds.
46+
47+
## Shell Navigation
48+
49+
- Use Shell as the primary navigation host.
50+
- Register routes with `Routing.RegisterRoute(...)` and navigate with `Shell.Current.GoToAsync(...)`.
51+
- Set `MainPage` once at startup; avoid changing it frequently.
52+
- Don't nest tabs inside Shell.
2753

2854
## Error Handling and Validation
2955

3056
- Implement proper error handling for .NET MAUI pages and API calls.
31-
- Use logging for error tracking in the backend and consider capturing UI-level errors in MAUI with tools like MAUI Community Toolkit's Logger.
57+
- Use logging for app-level errors; log and surface user-friendly messages for recoverable failures.
3258
- Implement validation using FluentValidation or DataAnnotations in forms.
3359

3460
## MAUI API and Performance Optimization
3561

36-
- Utilize MAUI's built-in features for component lifecycle (e.g. OnAppearing, OnDisappearing).
37-
- Use asynchronous methods (async/await) for API calls or UI actions that could block the main thread.
38-
- Optimize MAUI components by reducing unnecessary renders and using OnPropertyChanged() efficiently.
39-
- Minimize the component render tree by avoiding re-renders unless necessary, using BatchBegin() and BatchCommit() where appropriate.
62+
- Prefer compiled bindings for performance and correctness.
63+
- In XAML, set `x:DataType` on pages/views/templates.
64+
- Prefer expression-based bindings in C# where possible.
65+
- Consider enabling stricter XAML compilation in project settings (for example `MauiStrictXamlCompilation=true`), especially in CI.
66+
- Avoid deep layout nesting (especially nested StackLayouts). Prefer Grid for complex layouts.
67+
- Keep bindings intentional:
68+
- Use `OneTime` when values don't change.
69+
- Use `TwoWay` only for editable values.
70+
- Avoid binding static constants; set them directly.
71+
- Update UI from background work using `Dispatcher.Dispatch()` or `Dispatcher.DispatchAsync()`:
72+
- Prefer `BindableObject.Dispatcher` when you have a reference to a Page, View, or other BindableObject.
73+
- Inject `IDispatcher` via DI when working in services or ViewModels without direct BindableObject access.
74+
- Use `MainThread.BeginInvokeOnMainThread(...)` as a fallback only when no Dispatcher is available.
75+
- **Avoid** obsolete `Device.BeginInvokeOnMainThread` patterns.
4076

41-
## Caching Strategies
77+
## Resources and Assets
4278

43-
- Implement in-memory caching for frequently used data, especially for MAUI apps. Use IMemoryCache for lightweight caching solutions.
44-
- Consider Distributed Cache strategies (like Redis or SQL Server Cache) for larger applications that need shared state across multiple users or clients.
45-
- Cache API calls by storing responses to avoid redundant calls when data is unlikely to change, thus improving the user experience.
79+
- Place images in `Resources/Images/`, fonts in `Resources/Fonts/`, and raw assets in `Resources/Raw/`.
80+
- Reference images as PNG/JPG (e.g., `<Image Source="logo.png" />`), not `.svg`.
81+
- Use appropriately sized images to avoid memory bloat.
4682

47-
## State Management Libraries
83+
## State Management
4884

49-
- Use dependency injection and the .NET MAUI Community Toolkit for state sharing across components.
85+
- Prefer DI-managed services for shared state and cross-cutting concerns; keep ViewModels scoped to navigation/page lifetimes.
5086

5187
## API Design and Integration
5288

5389
- Use HttpClient or other appropriate services to communicate with external APIs or your own backend.
5490
- Implement error handling for API calls using try-catch and provide proper user feedback in the UI.
5591

92+
## Storage and Secrets
93+
94+
- Use `SecureStorage` for secrets (tokens, refresh tokens), and handle exceptions (unsupported device, key changes, corruption) by clearing/resetting and re-authenticating.
95+
- Avoid storing secrets in Preferences.
96+
5697
## Testing and Debugging
5798

5899
- Test components and services using xUnit, NUnit, or MSTest.
@@ -63,7 +104,10 @@ applyTo: '**/*.xaml, **/*.cs'
63104
- Implement Authentication and Authorization in the MAUI app where necessary using OAuth or JWT tokens for API authentication.
64105
- Use HTTPS for all web communication and ensure proper CORS policies are implemented.
65106

66-
## API Documentation and Swagger
107+
## Common Pitfalls
67108

68-
- Use Swagger/OpenAPI for API documentation for your backend API services.
69-
- Ensure XML documentation for models and API methods for enhancing Swagger documentation.
109+
- Changing `MainPage` frequently can cause navigation issues.
110+
- Gesture recognizers on both parent and child views can conflict; use `InputTransparent = true` where needed.
111+
- Memory leaks from unsubscribed events; always unsubscribe and dispose resources.
112+
- Deeply nested layouts hurt performance; flatten the visual hierarchy.
113+
- Testing only on emulators misses real-device edge cases; test on physical devices.

0 commit comments

Comments
 (0)