# A service captures its construction dependencies

> For agents: start with the [agent guide](https://ratstack.sh/llms.txt). Every page is Markdown by default; add `Accept: text/html` for HTML.

New on /news: [Foldkit joins Effect as its full-stack framework](/news).

A service is a named interface. A Layer describes how to build a service and supply its dependencies.
A context holds supplied service implementations.

Build a service once with the dependencies its implementation needs. Return methods that use those captured values.
Callers then require only the service.

## Name the job before the implementation

`Context.Service` names a service and describes its interface.
`Effect.Effect<FileStats, FileStatsError>` declares the method's success and [expected failure](/lore/error-model). Its omitted requirement parameter is `never`.

packages/core/src/file-inspector.ts at 65e9465f38092e24486392f22c08f45d61230c20; lines 6-15; highlighted none.

```typescript
export class FileInspector extends Context.Service<
  FileInspector,
  {
    readonly inspect: (
      path: string
    ) => Effect.Effect<FileStats, FileStatsError>;
  }
>()("@rat-stack/core/FileInspector", {
  make: Effect.gen(function* makeFileInspector() {
    const fileSystem = yield* FileSystem.FileSystem;
```

`make` describes service construction as an Effect.
`Layer.effect` runs that construction when the service graph is built.

## Compose work inside the method

Use `Effect.gen` for inline composition. Use `Effect.fn("name")` for reusable functions that need a tracing boundary.
Use `Effect.fnUntraced` when tracing is not useful.
Do not create a function that only returns another `Effect.gen` wrapper.

packages/core/src/file-inspector.ts at 65e9465f38092e24486392f22c08f45d61230c20; lines 17-35; highlighted none.

```typescript
    const inspect = Effect.fn("FileInspector.inspect")(function* inspect(
      path: string
    ) {
      const content = yield* fileSystem
        .readFile(path)
        .pipe(
          Effect.mapError(
            (error) => new FileStatsError({ path, reason: error.message })
          )
        );

      return summarizeBytes(path, content);
    });

    return { inspect } as const;
  }),
}) {
  static readonly layer = Layer.effect(this, this.make);
}
```

`inspect` retains the filesystem value captured during construction. It keeps read failures typed and returns a domain result.

The service method composes Effects. It does not run a separate runtime that executes the work immediately inside the computation.

## Construction dependencies are not request identity

Methods can retain contextual requirements when the job needs them.
A filesystem implementation usually belongs to construction. A current person may belong to a single request.

Pass request data explicitly, or keep that requirement visible at the request boundary.
Do not capture one request's identity in a service shared by later requests.

[Issue #24](https://github.com/kitlangton/effect-solutions/issues/24) records the risk of treating dependency-free methods as universal law.

## Common wrong approach

Resolving the filesystem inside every `inspect` call leaves `FileSystem` in that method's requirements.
The caller must now know the implementation dependency. Capturing it during construction removes that requirement from the method.

Rebuilding the service inside every call also loses the intended construction lifetime.
Supply its Layer at the [composition root](/lore/layers-make-dependencies-explicit), the startup code that chooses and supplies implementations.

## Effect idiom and house rule

- Services describe behavior. Layers supply implementations and resolve construction requirements.
- In rat-stack, keep `make` and `static layer` beside the service. Core owns service interfaces named for application jobs; adapters own provider code.
- rat-stack also uses capability projections, cartridge packages, and a no-comments rule.

See also: [domain structure](/lore/structure-effect-by-domain), [Layer composition](/lore/layers-make-dependencies-explicit), [the Layer constructor pattern](/lore/layer-constructor-pattern), and [testing through services](/lore/tests-that-earn-their-place).

Read [why dependency injection matters](/lore/dependency-injection-is-the-reason-to-choose-effect).

## Sources

1. [Effect contributors. 2026. Context. Effect 4.0.0.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/packages/effect/src/Context.ts)
   Effect-TS. Context.Service supports a typed interface and an effectful make operation. Accessed 2026-10-06.

2. [Effect contributors. 2026. Composing services with the Layer module.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/ai-docs/src/01_effect/03_services/20_layer-composition.ts)
   Effect-TS. Construction captures dependencies before returning Effect.fn methods. Accessed 2026-10-06.

3. [Effect contributors. 2026. Effect. Effect 4.0.0.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/packages/effect/src/Effect.ts)
   Effect-TS. Effect.gen composes inline work; fn names traced functions; fnUntraced avoids tracing. Accessed 2026-10-06.

4. [rat-stack contributors. 2026. FileInspector.](https://github.com/joelhooks/rat-stack/blob/65e9465f38092e24486392f22c08f45d61230c20/packages/core/src/file-inspector.ts)
   rat-stack. The service captures FileSystem in make and exposes an inspect method without filesystem requirements. Accessed 2026-10-06.

5. [Langton, Kit. 2026. Services & Layers. Effect Solutions.](https://github.com/kitlangton/effect-solutions/blob/09f82e6c5c928e7232cd32daf04d7c6a830b63f7/packages/website/docs/04-services-and-layers.md)
   Kit Langton. Topic framing for service interfaces, dependency capture, and replaceable implementations; examples checked against Effect 4.0.0. Accessed 2026-10-06.

6. [Effect Solutions contributors. 2025. Clarify that there could be exceptions on methods having dependencies.](https://github.com/kitlangton/effect-solutions/issues/24)
   Effect Solutions. Reader concern about request-time context and universal dependency-free method advice. Accessed 2026-10-06.

## Lore on this page

- [A cartridge owns one job and its resources](/lore/cartridges)

## Linked from

- A Layer as constructor → Sam Goodwin compares an Effect Layer that builds a service to a constructor. → [Read page](https://ratstack.sh/lore/layer-constructor-pattern)

- add-a-feature-flag → Declare a typed feature flag, its scoped evidence ladder, approval roles, removal date, and durable ledger adapter. → [Read page](https://ratstack.sh/skills/add-a-feature-flag)

- Admission control protects recovery → Refuse or defer work that cannot be served usefully under current load. → [Read page](https://ratstack.sh/lore/admission-controls-new-work)

- Agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms.txt)

- Bindings → Sam Goodwin describes bindings as the place where runtime permissions and configuration meet infrastructure. → [Read page](https://ratstack.sh/lore/bindings)

- Change log → What changed in the files served here, newest first. → [Read page](https://ratstack.sh/log)

- Cleanup can be an idempotent postcondition → Already-absent state can be success when absence is the operation’s intended result. → [Read page](https://ratstack.sh/lore/cleanup-can-be-an-idempotent-postcondition)

- Configuration is a supplied, validated dependency → Parse configuration when a Layer builds, reject invalid values, and supply controlled settings in tests. → [Read page](https://ratstack.sh/lore/configuration-is-a-dependency)

- Context and requirements → Effect requirements make a computation's needed services visible in its type. → [Read page](https://ratstack.sh/lore/context-and-requirements)

- Dependency injection is the reason to choose Effect → Effect tracks service requirements in types and supplies replaceable implementations through Layers. → [Read page](https://ratstack.sh/lore/dependency-injection-is-the-reason-to-choose-effect)

- durability → Keep a rat-stack app standing when a provider, pool, or dependency slows down or a worker dies. Use at any I/O boundary, connection pool, provider call, shared waiter, fan-out, flag, gate, or work that can outlive a request, or when asked "what happens when this is slow", "add a timeout", "make this durable", or "what survives a crash". → [Read page](https://ratstack.sh/skills/durability)

- Durability bibliography → Books, checked short quotations, source limits, and Effect mapping provenance. → [Read page](https://ratstack.sh/lore/durability-bibliography)

- Durable work needs storage → A restarted worker cannot recover intent that existed only in memory. → [Read page](https://ratstack.sh/lore/durable-work-needs-storage)

- Effect basics → An Effect describes work, expected failures, and required services before a runtime executes it. → [Read page](https://ratstack.sh/lore/effect-basics)

- Effect keeps the surfaces on one contract → Schema owns values, projections build interfaces, and Layers supply implementations. → [Read page](https://ratstack.sh/lore/how-we-do-it-with-effect)

- Failures keep their meaning → Expected refusals, infrastructure faults, and defects need different policies. → [Read page](https://ratstack.sh/lore/failures-keep-their-meaning)

- Feature flags → Typed feature flags with owners, removal dates, and stable subject rollouts. → [Read page](https://ratstack.sh/systems/flags)

- Full agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms-full.txt)

- Golden signals expose overload → Measure latency, traffic, errors, and saturation, including failed work. → [Read page](https://ratstack.sh/lore/golden-signals-expose-overload)

- Infrastructure as effects → Sam Goodwin relates application operations to infrastructure requirements in one typed program. → [Read page](https://ratstack.sh/lore/infrastructure-as-effects)

- Layer composition makes dependencies explicit → Supply a service's dependencies, choose which services remain visible, and reuse Layer identity within a build. → [Read page](https://ratstack.sh/lore/layers-make-dependencies-explicit)

- Learn rat-stack from your own agent → Turn on learn mode: your own agent explains rat-stack ideas during real work and keeps progress local. → [Read page](https://ratstack.sh/learn)

- learn-rat-stack → Trace a capability through Effect, XState, five projections, the CLI, and Alchemy. Try hosted search and read. → [Read page](https://ratstack.sh/skills/learn-rat-stack)

- Pure cores reduce timeline coupling → Move deterministic rules out of time-dependent actions and shared mutable state. → [Read page](https://ratstack.sh/lore/pure-cores-reduce-timelines)

- Rat Stack lore | rat-stack → Short, source-grounded notes on the ideas and decisions behind rat-stack. → [Read page](https://ratstack.sh/lore)

- Run Effect at the integration boundary → Build the runtime where a calling framework enters, reuse its services, and dispose it when that integration ends. → [Read page](https://ratstack.sh/lore/run-effect-at-the-boundary)

- Schemas define the boundary → Define accepted data with Schema, decode unknown input before dispatch, and encode results through the declared contract. → [Read page](https://ratstack.sh/lore/schemas-define-the-boundary)

- Source change history (log.md) → The generated change log as Markdown. → [Read page](https://ratstack.sh/log.md)

- Structure an Effect codebase by domain → Start with folders for application work, services and Layers in the same file, and startup code that supplies implementations. → [Read page](https://ratstack.sh/lore/structure-effect-by-domain)

- Timeouts bound waiting → A local timeout stops waiting; it does not prove the remote action never happened. → [Read page](https://ratstack.sh/lore/timeouts-bound-waiting)

## Unlinked mentions

- [A cartridge owns one job and its resources](https://ratstack.sh/lore/cartridges) → A service is the named interface callers use for that job.

- [A clean playground](https://ratstack.sh/lore/a-clean-playground) → Its database cartridge owns a RunLog service and Layers for two database implementations.¶

- [A Layer as constructor](https://ratstack.sh/lore/layer-constructor-pattern) → A service is the named interface callers use for a job.¶

- [add-a-capability](https://ratstack.sh/skills/add-a-capability) → A service is a named interface for one job.

- [add-a-feature-flag](https://ratstack.sh/skills/add-a-feature-flag) → Test this path with a service that denies every other call.¶

- [add-a-lifecycle-machine](https://ratstack.sh/skills/add-a-lifecycle-machine) → A service is a named interface for one job.

- [add-a-store](https://ratstack.sh/skills/add-a-store) → A service is a named interface for one job.

- [Admission control protects recovery](https://ratstack.sh/lore/admission-controls-new-work) → An overloaded service keeps accepting work and extends its own outage.¶

- [Agent rules for rat-stack (AGENTS.md)](https://ratstack.sh/AGENTS.md) → 0 in prepare so the Effect language service diagnostics in tsconfig.base.json fail tsc, not just the editor.

- [An MCP your users want](https://ratstack.sh/lore/an-mcp-your-users-want) → OAuth lets a person authorize a client to access a service.¶

- [Analytics](https://ratstack.sh/systems/analytics) → A service is a named interface for one job.¶

- [Anti-money](https://ratstack.sh/lore/anti-money) → Sam describes Alchemy as “anti-money”: reduce software sold as a service (SaaS) to libraries, then ask what remains valuable to manage.

- [Build and run rat-stack (README.md)](https://ratstack.sh/README.md) → Role: Public content graph and traversal service

- [Capabilities](https://ratstack.sh/systems/capabilities) → A service is a named interface for one job.

- [Cleanup can be an idempotent postcondition](https://ratstack.sh/lore/cleanup-can-be-an-idempotent-postcondition) → Put the domain meaning in the service contract; Effect supplies execution.

- [Code snippets quote a pinned source](https://ratstack.sh/lore/code-snippets) → A service is a named interface.

- [Concurrent work needs an owner and a bound](https://ratstack.sh/lore/concurrent-work-needs-an-owner) → Measure the service’s limits before selecting an operational bound.¶

- [Configuration is a supplied, validated dependency](https://ratstack.sh/lore/configuration-is-a-dependency) → A service is a named interface.

- [Context and requirements](https://ratstack.sh/lore/context-and-requirements) → The actor that does the read asks for that service by name:¶

- [Database](https://ratstack.sh/systems/database) → It gives callers one service, RunLog.

- [Dependency injection is the reason to choose Effect](https://ratstack.sh/lore/dependency-injection-is-the-reason-to-choose-effect) → The compiler rejects execution while a required service remains in R.¶

- [Devtools](https://ratstack.sh/systems/devtools) → A service is a named interface for one job.¶

- [durability](https://ratstack.sh/skills/durability) → Use: A Durable Object adapter behind an Effect service¶

- [Durability bibliography](https://ratstack.sh/lore/durability-bibliography) → Chapter 9 Microservices Using Function-as-a-Service¶

- [Effect + Alchemy peer patterns](https://ratstack.sh/resources/same-version-repos) → The browser calls a same-origin TanStack /rpc route, which forwards to a private BACKEND service binding; the backend has no public Workers URL.

- [Effect 4 study: September 2026](https://ratstack.sh/resources/effect-4-reference-projects) → These projects show Effect service, test, CLI, and lifecycle patterns.

- [Effect basics](https://ratstack.sh/lore/effect-basics) → A service is a named interface for work.

- [Effect's design lineage](https://ratstack.sh/lore/effect-design-lineage) → Dependency injection supplies service implementations to the code that needs them.

- [Feature flags](https://ratstack.sh/systems/flags) → Climbs use the capability approval service.

- [Fence](https://ratstack.sh/systems/fence) → A service is a named interface for one job.¶

- [Flags climb on evidence](https://ratstack.sh/lore/flags-climb-on-evidence) → That service authorizes the requested climb.

- [Golden signals expose overload](https://ratstack.sh/lore/golden-signals-expose-overload) → A service reports fast responses while errors rise or scarce capacity is exhausted.¶

- [Hexagonal architecture](https://ratstack.sh/lore/hexagonal-architecture) → Typed preparation for agent-assisted intake uses the same service boundary: IntakeTicket, AbuseScore, and IntakeEvents, question and consent schemas, and test layers live in core.

- [HTTP success needs a status check and a decoder](https://ratstack.sh/lore/http-responses-need-validation) → In rat-stack, core owns service interfaces named for application jobs.

- [Infrastructure as effects](https://ratstack.sh/lore/infrastructure-as-effects) → An Alchemy Layer can declare the cloud resources behind a service.

- [keep-or-cut](https://ratstack.sh/skills/keep-or-cut) → A service is a named interface for one job.¶

- [Layer composition makes dependencies explicit](https://ratstack.sh/lore/layers-make-dependencies-explicit) → A service is a named interface.

- [learn](https://ratstack.sh/skills/learn) → terse: show the service declaration and the line that uses or provides it.

- [Learn mode presents concepts at useful depths](https://ratstack.sh/systems/learn) → A service is a named interface for one job.¶

- [learn-alchemy](https://ratstack.sh/skills/learn-alchemy) → A service is a named interface for one job.

- [learn-rat-stack](https://ratstack.sh/skills/learn-rat-stack) → A service is a named interface for one job.

- [Lint and type escape ledger (debt.md)](https://ratstack.sh/debt.md) → Reason: from must answer the tag’s service, not a number.

- [Michael Arnaldi](https://ratstack.sh/lore/michael-arnaldi) → Dependency injection supplies service implementations to callers.

- [Purpose and boundaries of rat-stack (VISION.md)](https://ratstack.sh/VISION.md) → New code takes the rat-stack path: a shared contract, a job-shaped service port, a provider adapter outside core, and an outcome you can observe.

- [Rat's Nest keeps the code public and the inventory private](https://ratstack.sh/lore/rats-nest) → Cartridges explain rat-stack’s service and infrastructure pattern.¶

- [Run Effect at the integration boundary](https://ratstack.sh/lore/run-effect-at-the-boundary) → A service is a named interface.

- [Schema projections: 2026-09-18 history](https://ratstack.sh/resources/schema-projections-and-code-mode) → Casts live at exactly two boundaries per projection (tuple-to-record and handler record), each with a reason; the two projection files turn off three language-service diagnostics that cannot tell a typed boundary from a leak.

- [Scopes release resources when work ends](https://ratstack.sh/lore/scopes-own-resources) → A service Layer can own that resource for its build lifetime.

- [security-audit](https://ratstack.sh/skills/security-audit) → high — an actor fully defeats an explicit security control with real consequences: authentication bypass, cross-tenant read or write, stored script execution affecting other users, authenticated code execution, or an unauthenticated remote stop of a shared service.¶

- [Shared caches hold completed values](https://ratstack.sh/lore/cache-completed-values) → rat-stack-patterns/no-shared-pending-cache rejects these cache constructors in module, service, and Worker initialization effects.

- [ship](https://ratstack.sh/skills/ship) → Service: a named interface for one job.¶

- [Structure an Effect codebase by domain](https://ratstack.sh/lore/structure-effect-by-domain) → A service is a named interface for that work.

- [test-behaviour](https://ratstack.sh/skills/test-behaviour) → An example test fits one interface between parts, such as a service over the real filesystem.

- [Tests prove behavior through supplied services](https://ratstack.sh/lore/tests-that-earn-their-place) → A service is a named interface.

- [The fence](https://ratstack.sh/lore/the-fence) → Effect language-service diagnostics run through TypeScript.

- [uncomplect](https://ratstack.sh/skills/uncomplect) → Service: A named interface for one job.

- [Worker init runs twice](https://ratstack.sh/lore/init-runs-twice) → The runtime did not have that deploy-time service, so production returned error 1101 for about three minutes.¶
