Logo de Uw Dependency Injection

Uw Dependency Injection

Comunidade
devdavv
uw-dependency-injection

Opt-in DI architecture using Reflex for Unity 6+. Covers container setup, scoping, injection, command pattern, update management, and class taxonomy. Use when ProjectConfig.yaml -> architecture_pattern is "di-first", or when the user asks about dependency injection, inversion of control, service architecture, or testable game code. Triggers on "set up DI", "add dependency injection", "create a service", "wire up dependencies", "make this testable", "decouple these systems", "add a command pattern", "cross-feature communication", or architecture discussions involving testability, decoupling, and service layers. Only activates when ProjectConfig.yaml -> architecture_pattern is "di-first". For simpler projects, use uw-scriptable-object-arch instead.

Visão geral

Publicado pordevdavv
Repositóriounity-ai-workflow
Nome da habilidadeuw-dependency-injection
Estrelas
46
Forks
6
Arquivos incluídos
1
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • 1 arquivos incluídos

    Scripts, modelos de documentos e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente leitura e nunca são executados.

  • Código aberto

    Publicada por devdavv no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Uw Dependency Injection no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/devdavv/unity-ai-workflow/tree/main/.claude/skills/uw-dependency-injection
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/devdavv/unity-ai-workflow.git /tmp/unity-ai-workflow
mkdir -p .claude/skills
cp -r /tmp/unity-ai-workflow/.claude/skills/uw-dependency-injection .claude/skills/uw-dependency-injection
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Uw Dependency Injection em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Uw Dependency Injection automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Uw Dependency Injection não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Dependency Injection (Reflex)

DI-first architecture for complex Unity projects. Only applies when ProjectConfig.yaml -> architecture_pattern: di-first. For simpler projects, use uw-scriptable-object-arch (SO-first) instead.

Before You Start

  1. Read docs/ProjectConfig.yaml for:
    • architecture_pattern — must be "di-first" for this skill to apply.
    • di_framework — should be "reflex" (the default and recommended framework).
    • mcp.unity_mcp — if true, call refresh_unity after creating files.
  2. Read docs/CODING_STANDARDS.md for async patterns (Awaitable + CancellationToken), access modifiers (internal for cross-class helpers within an asmdef), and class structure.
  3. Read docs/NAMING_CONVENTIONS.md for file/class naming.
  4. Ensure each feature module has its own .asmdef — create with uw-unity-feature-scaffold. Installers, Controllers, Services all live inside feature asmdefs.

When to Use DI vs SO-First

SO-First (default)DI-First
Small/medium scopeLarge/complex scope
Solo or small teamTeam with testing culture
Rapid prototypingProduction architecture
Simple event-driven communicationCross-feature orchestration via Commands
ScriptableObject event channelsInterface-based injection + factories

Both can coexist: DI containers can bind ScriptableObject data assets as singletons.

Reflex Setup

Install (OpenUPM): openupm install com.gustavopsantos.reflex Or UPM Git URL: https://github.com/gustavopsantos/reflex.git?path=/Assets/Reflex/

Container Hierarchy

RootScope (app lifetime — singletons, core services)
  +-- SceneScope (scene lifetime — per-scene services, controllers)
        +-- Manual child scopes (gameplay round, level, etc.)

Installer Pattern

Each feature module has one Installer that registers its bindings. The Installer lives inside the feature's .asmdef.

csharp
using Reflex.Core;
using UnityEngine;

namespace {RootNamespace}.Core
{
    public class CoreInstaller : MonoBehaviour, IInstaller
    {
        [SerializeField] private AudioSettingsData _audioSettings;

        public void InstallBindings(ContainerBuilder builder)
        {
            // Services (singleton, app lifetime)
            builder.AddSingleton(typeof(IAudioService), typeof(AudioService));
            builder.AddSingleton(typeof(IStateMachineService), typeof(StateMachineService));

            // SO data (inject existing asset as value)
            builder.AddInstance(_audioSettings);
        }
    }
}

Binding Types

MethodWhat It DoesLifetime
AddSingleton(type, impl)Container creates one instanceApp/Scene
AddTransient(type, impl)New instance each resolvePer-resolve
AddInstance(obj)Register existing object (SO, config)Singleton

Injection

csharp
using Reflex.Attributes;

namespace {RootNamespace}.Combat
{
    public class ArrowController
    {
        [Inject] private readonly IAudioService _audio;
        [Inject] private readonly IArrowMovementController _movement;

        // OR constructor injection (preferred for non-MonoBehaviours):
        public ArrowController(IAudioService audio, IArrowMovementController movement)
        {
            _audio = audio;
            _movement = movement;
        }
    }
}

Constructor injection is preferred for plain C# classes — it makes dependencies explicit and prevents forgetting to inject. Use [Inject] attribute injection for MonoBehaviours (which Unity constructs).

Interface-First Rule

Always bind to interfaces, not concrete types. This enables mock injection for testing, makes dependencies explicit, and follows the Dependency Inversion Principle.

csharp
// Correct — bind to interface
builder.AddSingleton(typeof(IAudioService), typeof(AudioService));

// Wrong — binding concrete directly prevents mock injection
builder.AddSingleton(typeof(AudioService));

Circular Dependency Prevention

Circular dependencies (A depends on B, B depends on A) cause infinite resolution loops. Prevent them with:

  1. Commands — if two features need to communicate, use a Command that resolves its deps at execution time instead of at construction time.
  2. Events / ScriptableObject channels — decouple with uw-scriptable-object-arch event channels.
  3. Interfaces in a shared assembly — extract the interface into {RootNamespace}.Core.asmdef so both features depend on the interface, not on each other.

If the container throws a circular dependency error, trace the dependency chain and break it at the point where a Command or event channel makes more sense than a direct reference.

App Lifecycle / Single Entry Point (SEP)

Only one scene has a Start() method. All other initialization flows from there.

CoreScene loads -> RootScope binds -> CoreInitiator.Start()
  -> Load GameScene (additively) -> SceneScope binds -> GameInitiator.Init()
    -> Load GamePlayScene -> SceneScope binds -> GamePlayInitiator.Init()

Rules:

  • CoreScene is always the first scene (set in Build Settings index 0, or via editor DefaultSceneSelector).
  • Each scene has one Installer (bindings) and one Initiator (entry/exit points).
  • Only CoreInitiator has a Start() method — everything else is initialized via async InitEntryPoint().

Class Taxonomy, Commands & Update Management

See references/class-taxonomy-and-commands.md for the full 9-class taxonomy, Command pattern, and centralized Update management.

Key rule: Commands are the ONLY classes allowed to cross feature boundaries. This prevents circular dependencies — each Command resolves its own references from the DI container at execution time.

Cross-Feature Command Example

When Feature A (Combat) needs to notify Feature B (Score) about a hit:

csharp
// Lives in a shared Commands assembly or in the feature that initiates it
public class OnHitScoredCommand : ICommand
{
    [Inject] private readonly IScoreController _score;
    [Inject] private readonly IAudioService _audio;

    public void Execute()
    {
        _score.AddPoints(10);
        _audio.PlayOneShot(AudioClipType.Hit);
    }
}

The Combat feature doesn't reference Score directly — it resolves and executes the Command, which the container wires up. Register in the installer: builder.AddTransient(typeof(OnHitScoredCommand));

Integration with ScriptableObject Data

DI and SO work together — SO holds data, DI manages services and wiring:

csharp
// In installer: inject SO data asset into container
[SerializeField] private WeaponDatabase _weaponDatabase;

public void InstallBindings(ContainerBuilder builder)
{
    builder.AddInstance(_weaponDatabase); // SO data available via [Inject]
}

See uw-scriptable-object-arch for data container and event channel patterns that complement DI.

After Setup

  • Scaffold features: Use uw-unity-feature-scaffold to create feature modules with their own .asmdef — each feature gets its own Installer.
  • State management: Use uw-state-machine for game flow states, with states receiving dependencies via constructor injection.
  • Write tests: Use uw-unity-test-runner — interface-based DI makes testing easy: construct classes with mock dependencies, no container needed in tests.
  • SO data: Use uw-scriptable-object-arch for game data assets that get injected into services via AddInstance.

Rules

  • Only applies when ProjectConfig.yaml -> architecture_pattern: di-first.
  • Always bind to interfaces, not concrete types (interface-first rule).
  • Constructor injection preferred for plain C# classes. [Inject] attribute for MonoBehaviours.
  • Commands are the ONLY classes allowed to cross feature boundaries.
  • Each feature module needs its own .asmdef (per NAMING_CONVENTIONS.md). Installers live inside the feature's asmdef.
  • [SerializeField] private for Inspector-exposed fields on Installers and MonoBehaviours — never public fields.
  • Use Awaitable with CancellationToken for async operations (per CODING_STANDARDS.md).
  • CoreScene is Build Settings index 0. Only CoreInitiator has Start().
  • Break circular dependencies with Commands, events, or shared interface assemblies — never with direct cross-feature references.
  • If ProjectConfig.yaml -> mcp.unity_mcp is true, call refresh_unity after creating files.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Uw Dependency Injection faz?

Opt-in DI architecture using Reflex for Unity 6+. Covers container setup, scoping, injection, command pattern, update management, and class taxonomy. Use when ProjectConfig.yaml -> architecture_pattern is "di-first", or when the user asks about dependency injection, inversion of control, service architecture, or testable game code. Triggers on "set up DI", "add dependency injection", "create a service", "wire up dependencies", "make this testable", "decouple these systems", "add a command pattern", "cross-feature communication", or architecture discussions involving testability, decoupling,...

Por que usar Uw Dependency Injection no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Uw Dependency Injection é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Uw Dependency Injection no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/devdavv/unity-ai-workflow/tree/main/.claude/skills/uw-dependency-injection. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Uw Dependency Injection?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Uw Dependency Injection?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Uw Dependency Injection com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Uw Dependency Injection é gratuita?

Sim. A habilidade é publicada no GitHub por devdavv sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇