Dependency Injection logo

Dependency Injection

Community
psincraian
dependency-injection

myfy dependency injection with scopes (SINGLETON, REQUEST, TASK). Use when working with @provider decorator, DI container, scopes, injection patterns, or understanding how WebModule, DataModule, FrontendModule, TasksModule, UserModule, CliModule, AuthModule, and RateLimitModule use dependency injection.

Overview

Publisherpsincraian
Repositorymyfy
Skill namedependency-injection
Stars
88
Forks
1
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by psincraian on GitHub. Read the source before you install it.

Installation

Install the Dependency Injection AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/psincraian/myfy.git /tmp/myfy
mkdir -p .claude/skills
cp -r /tmp/myfy/plugins/claude-code/skills/dependency-injection .claude/skills/dependency-injection
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Dependency Injection in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Dependency Injection on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Dependency Injection is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Dependency Injection in myfy

myfy uses constructor-based dependency injection with three scopes.

Scopes

ScopeLifetimeUse Case
SINGLETONApplication lifetimeConfig, pools, services, caches
REQUESTPer HTTP requestSessions, user context, request logger
TASKPer background taskTask context, job-specific state

Provider Declaration

python
from myfy.core import provider, SINGLETON, REQUEST, TASK

# SINGLETON: Created once, shared across all requests
@provider(scope=SINGLETON)
def database_pool(settings: DatabaseSettings) -> DatabasePool:
    return DatabasePool(settings.database_url)

# REQUEST: Created per HTTP request, auto-cleaned up
@provider(scope=REQUEST)
def db_session(pool: DatabasePool) -> AsyncSession:
    return pool.get_session()

# TASK: Created per background task execution
@provider(scope=TASK)
def task_logger(ctx: TaskContext) -> Logger:
    return Logger(task_id=ctx.task_id)

Provider Options

python
@provider(
    scope=SINGLETON,              # Lifecycle scope
    qualifier="primary",          # Optional qualifier for multiple providers
    name="my_database",           # Optional name for resolution
    reloadable=("log_level",),    # Settings that can hot-reload
)
def database(settings: Settings) -> Database:
    return Database(settings.db_url)

Scope Dependency Rules

  1. SINGLETON can depend on: other singletons only
  2. REQUEST can depend on: singletons and other request-scoped
  3. TASK can depend on: singletons and other task-scoped

SINGLETON cannot depend on REQUEST/TASK - this fails at compile time!

python
# WRONG - will fail at startup
@provider(scope=SINGLETON)
def bad_service(session: AsyncSession):  # AsyncSession is REQUEST scope
    return MyService(session)

# CORRECT - use factory pattern
@provider(scope=SINGLETON)
def service_factory(pool: DatabasePool) -> ServiceFactory:
    return ServiceFactory(pool)

@provider(scope=REQUEST)
def service(factory: ServiceFactory, session: AsyncSession) -> MyService:
    return factory.create(session)

Injection in Routes

Parameters are auto-classified in order:

  1. Path parameters - from URL template like {user_id}
  2. Query parameters - annotated with Query(...) or primitives with defaults
  3. Body parameter - Pydantic model or dataclass
  4. DI dependencies - everything else (resolved from container)
python
from myfy.web import route, Query
from myfy.data import AsyncSession

@route.post("/users/{user_id}/orders")
async def create_order(
    user_id: int,                    # Path param
    limit: int = Query(default=10),  # Query param
    body: OrderCreate,               # Request body (Pydantic model)
    session: AsyncSession,           # DI (REQUEST scope)
    settings: AppSettings,           # DI (SINGLETON)
) -> dict:
    ...

Qualifiers for Multiple Providers

When you have multiple providers of the same type:

python
from myfy.core import provider, SINGLETON, Qualifier
from typing import Annotated

@provider(scope=SINGLETON, qualifier="primary")
def primary_db(settings: Settings) -> Database:
    return Database(settings.primary_url)

@provider(scope=SINGLETON, qualifier="replica")
def replica_db(settings: Settings) -> Database:
    return Database(settings.replica_url)

# Inject by qualifier
@route.get("/users")
async def list_users(
    db: Annotated[Database, Qualifier("replica")]
) -> list[dict]:
    return await db.fetch_all()

Common Patterns

Factory Pattern (REQUEST from SINGLETON)

python
@provider(scope=SINGLETON)
def email_client(settings: EmailSettings) -> EmailClient:
    return EmailClient(settings.api_key)

@provider(scope=REQUEST)
def email_sender(client: EmailClient, user: User) -> EmailSender:
    return EmailSender(client, from_user=user)

Optional Dependencies

python
from typing import Optional

@provider(scope=SINGLETON)
def cache_service(redis: Optional[RedisClient] = None) -> CacheService:
    if redis:
        return RedisCacheService(redis)
    return InMemoryCacheService()

Testing

Override providers in tests using the container's override context:

python
from myfy.core import override

async def test_with_mock_db():
    mock_db = MockDatabase()

    with override(Database, mock_db):
        # Inside this block, Database resolves to mock_db
        result = await my_service.do_something()

    assert result == expected

Best Practices

  1. Keep providers pure - No side effects in factory functions
  2. Use SINGLETON for shared resources - Database pools, HTTP clients, caches
  3. Use REQUEST for request-specific state - DB sessions, user context
  4. Use TASK for background job state - Task logger, job-specific clients
  5. Validate at compile time - All scope violations caught at startup
  6. Return type required - Provider functions must have return type annotation

Frequently asked questions

What does the Dependency Injection AI skill do?

myfy dependency injection with scopes (SINGLETON, REQUEST, TASK). Use when working with @provider decorator, DI container, scopes, injection patterns, or understanding how WebModule, DataModule, FrontendModule, TasksModule, UserModule, CliModule, AuthModule, and RateLimitModule use dependency injection.

Why use Dependency Injection on TypingMind?

Because you install it once and use it with any model. Dependency Injection is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Dependency Injection in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/psincraian/myfy/tree/main/plugins/claude-code/skills/dependency-injection. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Dependency Injection?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Dependency Injection?

As many as you like. As long as a model supports skills, you can use Dependency Injection with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Dependency Injection AI skill free?

It is published on GitHub by psincraian. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇