Expert MVVM et DI pour UI App

VérifiéSûr

Expert en pattern MVVM, ObservableObject, RelayCommand et injection de dépendances pour Unity App UI. Automatiquement activé pour la création de ViewModels, liaisons de données et enregistrement de services.

Spar Skills Guide Bot
DeveloppementIntermédiaire
27/07/2026
Claude CodeCursorWindsurfCopilotCodex
#unity#mvvm#dependency-injection#ui-toolkit#data-binding

Recommandé pour

Synthèse automatique

Guide l'implémentation d'interfaces Unity App UI selon le patron MVVM avec injection de dépendances : ObservableObject, RelayCommand, AppBuilder et enregistrement de services.

Points forts

  • Montre comment générer les notifications de changement et les commandes via les attributs [ObservableProperty] et [RelayCommand]
  • Détaille l'enregistrement des services dans AppBuilder.OnConfiguringApp() et les différents cycles de vie (singleton, transient, scoped)
  • Explique la liaison de données entre les vues UXML et les ViewModels, avec injection par constructeur ou attribut [Service]
  • Rappelle la séparation stricte des responsabilités : la vue ne contient aucune logique métier

Limites

  • Très spécifique à Unity UI Toolkit et au package App UI, inutilisable pour d'autres frameworks d'interface
  • Suppose une bonne maîtrise de C# (classes partielles, générateurs de source) et des namespaces Unity.AppUI.MVVM / Unity.Properties
  • N'aborde ni les tests unitaires des ViewModels ni la navigation entre écrans
Quand l'utiliser

À utiliser lorsqu'on crée ou refactorise une application Unity UI Toolkit en MVVM et qu'il faut écrire des ViewModels, des commandes ou câbler l'injection de dépendances.

Quand l'éviter

À éviter hors de Unity/App UI, ou pour une interface statique qui n'a besoin ni de liaison de données ni de services injectés.

Analyse de sécurité

Sûr
Score qualité80/100

The skill is purely instructional documentation for Unity's App UI MVVM and dependency injection. It contains no shell commands, no network calls, no file-system or credential operations, and nothing obfuscated. The declared tools (Bash, Read, Write, Edit, Glob, Grep) are broad but standard for a coding assistant that would scaffold ViewModels and register services; no instruction in the body tells the agent to use them for anything destructive or exfiltrating.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Create a bound ViewModel
Create a ViewModel for a settings screen in my Unity App UI project with a player name string and a volume float, using [ObservableProperty], and show me how to bind them to my UXML document.
Set up DI with AppBuilder
Set up an AppBuilder in my Unity project and register IPlayerService as a singleton and MainViewModel as transient, then inject the service into the ViewModel.
Add a button command
Add a [RelayCommand] to my MainViewModel that saves data through an injected service, and bind it to a Button in my UXML.

name: app-ui-mvvm description: "Expert for App UI MVVM pattern and dependency injection - ObservableObject, RelayCommand, AppBuilder, service registration, and DI. Use this skill whenever the user wants to create a ViewModel, bind data to UI elements, set up dependency injection, register services, implement commands for button actions, use [ObservableProperty] or [RelayCommand] attributes, create an AppBuilder, or structure their Unity App UI project with the MVVM architecture pattern. Also trigger when the user asks about data binding in UXML, property change notifications, or service lifetimes (transient, singleton, scoped)." allowed-tools: Bash, Read, Write, Edit, Glob, Grep

App UI MVVM & Dependency Injection Expert

Overview

The MVVM (Model-View-ViewModel) pattern is a design pattern that separates user interface from business logic. Combined with Dependency Injection (DI), it creates a powerful architecture for building maintainable, testable, and scalable applications using Unity's UI Toolkit.

When to Use MVVM

Use MVVM when you need to:

  • Separate UI concerns from business logic
  • Make your code testable and maintainable
  • Bind UI elements to data that changes dynamically
  • Handle complex user interactions with clean code organization
  • Enable designers and developers to work independently

Core Concepts

Model

The Model is a simple data structure containing the data used by business logic. It has no knowledge of the UI.

ViewModel

The ViewModel contains business logic and is responsible for:

  • Updating the Model when the user interacts with the View
  • Notifying the View when the Model changes (via property notifications)
  • Handling commands (user actions like button clicks)
  • Managing state and orchestrating operations

ViewModels connect to Views through data binding.

View

The View is the UI layer responsible for displaying data to the user. It should contain:

  • Only UI element definitions and styling logic
  • Event handlers that invoke ViewModel commands
  • Data bindings to ViewModel properties

Views should never contain business logic.

Key Namespaces

  • Unity.AppUI.MVVM - Core MVVM classes and DI
  • Unity.Properties - Property attributes and binding support

MVVM + Dependency Injection Architecture

┌─────────────────────────────────────────────┐
│            UIToolkitAppBuilder              │
│  (Configures app and services)              │
└──────────────────┬──────────────────────────┘
                   │
        ┌──────────┴──────────┐
        │                     │
        v                     v
   ┌─────────┐         ┌──────────────┐
   │   App   │         │ Service      │
   │         │         │ Collection   │
   └────┬────┘         └──────────────┘
        │
        v
   ┌──────────────────┐
   │   Views (UI)     │◄──── Data Binding ◄─── ViewModels
   │                  │      Commands           (Observable,
   └──────────────────┘                         RelayCommand)

Common Patterns

1. Observable Properties

Mark ViewModel properties with [ObservableProperty] to automatically generate property change notifications:

[ObservableObject]
public partial class MyViewModel
{
    [ObservableProperty]
    private string _name;
}

2. Relay Commands

Use [RelayCommand] attributes to auto-generate command properties:

[ObservableObject]
public partial class MyViewModel
{
    [RelayCommand]
    private void SaveData()
    {
        // Execute command logic
    }
}

3. Service Registration

Register services in AppBuilder.OnConfiguringApp():

appBuilder.services.AddSingleton<IMyService, MyService>();
appBuilder.services.AddTransient<MyViewModel>();

4. Service Injection

Inject services via constructor or [Service] attribute:

[ObservableObject]
public partial class MyViewModel
{
    [Service]
    public IMyService MyService { get; set; }
}

5. Dependent Properties

Use [AlsoNotifyChangeFor] to notify dependent properties:

[ObservableObject]
public partial class MyViewModel
{
    [ObservableProperty]
    [AlsoNotifyChangeFor(nameof(IsNameEmpty))]
    private string _name;

    public bool IsNameEmpty => string.IsNullOrEmpty(Name);
}

Best Practices

  1. Class Declaration: Classes with [ObservableObject] must be partial
  2. Field Naming: Observable fields must be private with underscore prefix (_fieldName)
  3. Constructor Injection: Prefer constructor injection for required dependencies
  4. Property Injection: Use [Service] attribute for optional dependencies
  5. Command Naming: Method names for [RelayCommand] should describe the action (e.g., SaveData, DeleteItem)
  6. Separation of Concerns: Keep business logic in ViewModels, UI logic in Views
  7. Service Lifetimes:
    • Use AddSingleton for stateless services (loggers, factories)
    • Use AddTransient for stateful services (ViewModels, Pages)
    • Use AddScoped for services tied to a specific scope

Command Patterns

Simple Commands

[RelayCommand]
void DoSomething() { }

Commands with Parameters

[RelayCommand]
void DoSomethingWith(string parameter) { }

Async Commands

[RelayCommand]
async Task DoSomethingAsync()
{
    await Task.Delay(1000);
}

Conditional Commands

[RelayCommand(CanExecute = nameof(CanSave))]
void Save() { }

private bool CanSave => !string.IsNullOrEmpty(Name);

Dependency Injection Lifetimes

  • Transient: New instance every time it's requested
  • Singleton: Same instance for the entire application lifetime
  • Scoped: Same instance within a scope, new instance for different scopes

UI Binding

ViewModels expose observable properties and commands that bind to UI elements:

<ui:Button title="Save">
    <Bindings>
        <ui:DataBinding property="clickable.command" binding-mode="ToTarget" data-source-path="SaveCommand"/>
        <ui:DataBinding property="enabledSelf" binding-mode="ToTarget" data-source-path="CanSave"/>
    </Bindings>
</ui:Button>

Related Features

  • State Management: Redux-like pattern for complex state
  • Navigation: Structured page navigation with parameters
  • Data Binding: Automatic UI updates from ViewModel changes
  • Commands: User action handling via RelayCommand

Reference Documentation

Consult reference.md when you need exact API signatures for ObservableObject, RelayCommand, AppBuilder, or service container methods, full attribute parameter lists, advanced DI patterns like scoped lifetimes, or details on IDependencyInjectionListener and [CreateProperty]. See examples/ for complete MVVM app setups with multiple ViewModels and services.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/app-ui-mvvm-di-expert-ms2s7buk/download' --output '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md.part' && mv '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md.part' '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Bash, Read, Write, Edit, Glob, Grep

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md' && test -s '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/app-ui-mvvm' && cp -R '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk' '.claude/skills/app-ui-mvvm'

Cursor
test -f '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md' && test -s '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/app-ui-mvvm' && cp -R '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk' '.cursor/skills/app-ui-mvvm'

Codex
test -f '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md' && test -s '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/app-ui-mvvm' && cp -R '.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk' '.agents/skills/app-ui-mvvm'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/app-ui-mvvm-di-expert-ms2s7buk'

openskills read 'app-ui-mvvm-di-expert-ms2s7buk'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/app-ui-mvvm-di-expert-ms2s7buk/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires