> ## Documentation Index
> Fetch the complete documentation index at: https://forst-lang.org/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Providers (DI)

> Declare shared runtime services and supply them at entry points.

Backend functions often depend on shared runtime services like loggers, database handles and other resources. **Providers** let you declare such dependencies with **`use`** and supply them at entry points using **`with`**. This way services don't need to be threaded through every parameter list, and tests can swap in fakes or mocks without changing the function under test.

## Two primitives

| Keyword | Role |
| - | - |
| **`use`** | Bind a contract type inside a function: "this code depends on X" |
| **`with { … } { … }`** | Wire concrete implementations at an entry point (handler, `main`, test) |

**Parameters continue carrying highly dynamic data** like request bodies. **Providers carry services** that typically rarely change (e.g. loggers, clocks and repositories). Keeping them separate clarifies what flows through your API boundary and what is ambient context.

## Declare dependencies with `use`

Contracts are ordinary types: shapes with methods, or imported Go interfaces:

> [tab] Forst
>
> ```ft theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> type Logger = {
> 	info(msg String)
> }
>
> type Clock = {
> 	now(): Int
> }
>
> func logExpiry(id String) {
> 	use logger: Logger
> 	logger.info("expire " + id)
> }
>
> func expireToken(token Token) {
> 	use clock: Clock
> 	if token.expiresAt < clock.now() {
> 		logExpiry(token.id)
> 	}
> }
> ```

> [tab] Generated Go
>
> ```go theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> // forst build
> type Logger interface {
> 	info(msg string)
> }
>
> type Clock interface {
> 	now() int
> }
>
> type Token struct {
> 	expiresAt int
> 	id        string
> }
>
> func logExpiry(providers Providers_logExpiry, id string) {
> 	providers.Logger.info("expire " + id)
> }
>
> func expireToken(providers Providers_expireToken, token Token) {
> 	clock := providers.Clock
> 	if token.expiresAt < clock.now() {
> 		logExpiry(providers, token.id)
> 	}
> }
> ```

The compiler aggregates `use` sites into **`Providers(f)`** for each function and propagates requirements transitively through calls. You can see the obligation chain in diagnostics and LSP hovers: which services a handler needs, and which entry point must supply them.

## Wire at the boundary

Entry points satisfy every Provider the call graph needs using a **`with { … } { … }`** block. Production wiring and test wiring use the same mechanism:

> [tab] Forst
>
> ```ft theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> func main() {
> 	with {
> 		Logger: &ProductionLogger{},
> 		Clock:  &SystemClock {},
> 	} {
> 		expireToken(Token { id: "x", expiresAt: 1 })
> 	}
> }
> ```

> [tab] Generated Go
>
> ```go theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> // forst build
> func main() {
> 	providers := Providers_expireToken{
> 		Logger: &ProductionLogger{},
> 		Clock:  &SystemClock{},
> 	}
> 	expireToken(providers, Token{id: "x", expiresAt: 1})
> }
> ```

Wiring keys use the **root contract name** (`Logger`, `Clock`). Values must structurally satisfy the contract: plain structs with matching methods, or Go types that implement an imported interface.

### Void contract methods

Contract methods without a return type (such as **`info(msg String)`**) must stay void on implementations.

* Do not end a void method with a Go call that returns values, such as **`fmt.Println(...)`**. With no declared return type, that trailing call becomes an implicit return, so the method no longer matches the void contract.
* Prefer Forst **`println`** / **`print`** when you only need a side effect, or declare an explicit return type when you intend to return the call result.

See [How a function gets that type](https://forst-lang.org/docs/language/result.md#how-a-function-gets-that-type).

### Shadowing

Nested **`with`** blocks merge with outer wiring. When the inner block supplies the **same contract key**, it **shadows** the outer value for that scope; other keys still forward from outside:

> [tab] Forst
>
> ```ft theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> with {
> 	Logger: &ProductionLogger {},
> 	Clock:  &SystemClock {},
> } {
> 	with { Clock: &FakeClock { fixedMs: 2000 } } {
> 		// Clock shadows outer; Logger still &ProductionLogger
> 		expireToken(Token { id: "t1", expiresAt: 500 })
> 	}
> }
> ```

> [tab] Generated Go
>
> ```go theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> // forst build
> outer := Providers_expireToken{
> 	Logger: &ProductionLogger{},
> 	Clock:  &SystemClock{},
> }
> inner := Providers_expireToken{
> 	Logger: outer.Logger,
> 	Clock:  &FakeClock{fixedMs: 2000},
> }
> expireToken(inner, Token{id: "t1", expiresAt: 500})
> ```

## Tests

Tests reuse the same `with` blocks to swap fakes without a separate DI framework:

> [tab] Forst
>
> ```ft theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> func TestExpireToken_expired(t *testing.T) {
> 	token := Token { id: "t1", expiresAt: 500 }
> 	with {
> 		Logger: &NopLogger {},
> 		Clock:  &FakeClock { fixedMs: 1000 },
> 	} {
> 		expireToken(token)
> 	}
> }
> ```

> [tab] Generated Go
>
> ```go theme={"theme":{"light":"github-light-default","dark":"dark-plus"}}
> // forst build
> func TestExpireToken_expired(t *testing.T) {
> 	token := Token{id: "t1", expiresAt: 500}
> 	providers := Providers_expireToken{
> 		Logger: &NopLogger{},
> 		Clock:  &FakeClock{fixedMs: 1000},
> 	}
> 	expireToken(providers, token)
> }
> ```

## Compared to other approaches

We surveyed these patterns before settling on **`use`** and **`with`**. See the [Providers RFC](https://github.com/forst-lang/forst/tree/main/examples/in/rfc/providers) for the full prior art writeup.

| Approach | Limitation |
| - | - |
| **Per function parameters** | Every helper gains extra arguments. Domain input and infrastructure blur together as the call graph grows. |
| **Go service struct** | Wiring lives in `main` as interface fields on one struct. A new dependency deep in the tree does not propagate to the compiler as a wiring obligation. |
| **`context.Context`** | `WithValue` is untyped. Keys are easy to miss or collide. Nothing tracks who must supply what at compile time. |
| **DI frameworks** (Fx, Wire, dig) | These tools rely on runtime containers or codegen indirection. Wiring and failures can be hard to trace in stack traces. |
| **Effect / ZIO Layers** | Requirements live in the environment type and runtime. Layer graphs add ceremony compared to one struct literal at the boundary. |
| **Kotlin context parameters** | Implicit context in signatures works on the JVM. Go has no native equivalent, and Forst lowers to explicit struct parameters. |
| **Test harness DSLs** | Special test-only keywords split production wiring from test wiring. Readers and agents learn two different surfaces. |
| **Mock frameworks** (Jest, testify) | Expectations couple tests to framework APIs. Structural fakes wired with the same boundary pattern as production are harder to reuse across integration tests. |
| **Global singletons** | Dependencies hide in package state. Tests need globals, init hooks, or monkey patching. |
| **Plain Go test helpers** | A hand written `newTestApp(t)` helper drifts from what handlers actually need. Nothing checks completeness when a leaf adds a new service. |
| **Forst `use` / `with`** | Obligations are inferred at compile time. Wiring stays explicit at entry points. The compiler emits plain Go struct literals with no runtime container. |

Forst treats `context.Context` separately from Providers. Declare services with **`use`** so requirements stay typed and visible. Use **`context`** for cancellation and request scoped values. Use **`with`** blocks for service wiring. Sidecar and TypeScript exports stay data only. The host wires Providers in Go before exposing a handler.

## What gets emitted

Providers lower to a **deduped struct parameter** at the Go boundary. Production and test wiring compile to ordinary struct literals: readable Go, no runtime container.

## Caveats

**Providers** are **experimental**. The RFC surface is still evolving. Pin your compiler version and check the [Providers examples](https://github.com/forst-lang/forst/tree/main/examples/in/rfc/providers) when upgrading.

### Host wiring only

Providers lower in Go. They are **not** exported to TypeScript or sidecar invoke payloads. Functions with unsatisfied **`Providers(f)`** are omitted from generated clients. Wire **`with`** blocks in Go **`main`** before exposing handlers.

See [Call Forst over HTTP § Caveats](https://forst-lang.org/docs/interop/invoke/call-forst.md#caveats) and [Generate client types § Caveats](https://forst-lang.org/docs/interop/invoke/generate-types.md#caveats).

### Void contract methods

* A trailing Go multi-return call such as **`fmt.Println(...)`** becomes an implicit return and breaks a void contract method.
* Prefer Forst **`println`** / **`print`** for side effects, or declare an explicit return type.

See [How a function gets that type](https://forst-lang.org/docs/language/result.md#how-a-function-gets-that-type).

### `context.Context` is separate

Providers do not replace Go's **`context.Context`**. They solve a different problem.

* **`context.Context`** remains the right place for cancellation, deadlines, and request-scoped values such as a request ID or trace span. Keep passing `ctx` as a normal parameter when a function needs those signals.
* **Providers** are for stable typed services declared with **`use`**: loggers, clocks, repositories, and similar host-supplied dependencies. The compiler tracks who must supply them at entry points.
* Avoid stuffing those services into **`context.WithValue`**. That pattern is untyped, easy to miss at call sites, and has no compile-time obligation chain. Providers exist so you do not need to overload `context` for DI.

A handler can take both. Use `context` for the request lifecycle, and Providers for the services the host supplies once and reuses across calls.

## Examples

See the provider examples on GitHub

* [`examples/in/rfc/providers/providers_demo/providers.ft`](https://github.com/forst-lang/forst/blob/main/examples/in/rfc/providers/providers_demo/providers.ft)
* [`examples/in/rfc/providers/cross_pkg/`](https://github.com/forst-lang/forst/tree/main/examples/in/rfc/providers/cross_pkg/)

Deep dive: [Providers RFC hub](https://github.com/forst-lang/forst/tree/main/examples/in/rfc/providers)

## Related

> [card] [Go interop](https://forst-lang.org/docs/interop/go.md)
>
> Import Go interfaces as Provider contracts.

> [card] [Editor workflow](https://forst-lang.org/docs/workflow/editor.md)
>
> LSP hovers show Provider obligations and related diagnostics.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.