{"canonical_url":"https://engineer.company/glossary/dependency-injection/","content_markdown":"# Dependency injection\n\n## What it is\n\nDependency injection supplies a component with the collaborators it needs. A\nservice that records reservations might receive a store and a clock when it is\nconstructed. Its logic can use those collaborators through the agreed behaviour,\nwhile another part of the program chooses the database implementation and how\nrequests get the current time.\n\nThe dependency can be passed through a constructor, a function argument or\nanother explicit setup step. Many frameworks offer a container that builds and\nwires components by configuration. The technique works with ordinary function\ncalls too. A composition point near program startup can select implementations,\nset up resources and hand the configured component to the routes or jobs that\nwill call it.\n\nLifetime is part of the arrangement. A process-wide manager may own a reusable\ndatabase pool. A request can open a transaction or carry per-request state. The\ncomponent must get the collaborator that fits its usage, and the program must\narrange cleanup when the relevant lifetime ends. A test can use a small\nsubstitute for the clock and a realistic store if it needs to exercise the\ntransaction boundary. Those choices belong where the test and the service are\nassembled.\n\n## Why it matters\n\nA component that constructs its own dependencies often combines several\ndecisions. It has to know how to calculate a result, where the data lives, how\ntime is obtained and which resources to close. It can also be difficult to\nexercise a failing store or a chosen expiry time without affecting other code.\nSupplying collaborators can make the inputs and the ownership of those choices\nclearer.\n\nUse a boundary that corresponds to real variation or a needed test. A reporting\ncomponent can receive an interface for obtaining a data snapshot. A test can\nmake that source fail at a known moment and check the response. A component that\ncan rely on a stable ordinary library function may be easier to read without a\nwrapper. Each introduced contract has a cost in how much callers and maintainers\nneed to learn.\n\nThe arrangement helps during changes to infrastructure. A new adapter can be\nconfigured at the composition point and tested with the component's existing\noperations. Keeping the business rules separate from the wiring does not remove\nthe need to test the adapter. Its timeouts, consistency and cleanup still\ninfluence outcomes. Supply a contract that explains what the caller can rely on,\nand exercise an implementation with the boundary it really uses.\n\n## What it looks like in practice\n\nImagine a service that gives customers a short reservation hold. It receives a\nclock and a store as constructor arguments. In production, a composition\nfunction builds a store backed by the application's database pool and supplies\nthe relevant clock. A focused test can supply a fixed time to check which side\nof a boundary an operation falls on. A separate integration exercise can use the\nreal store and verify the persisted state throughout a change.\n\nDefine lifetime alongside the wiring. A shared service can hold references to\nreusable collaborators that are safe across requests. It should receive a\nparticular transaction through the operation that uses it when a consistent\ntransactional boundary is required. Exercise concurrent calls and shutdown paths\nto check who owns cleanup. A lifetime mismatch can be hard to diagnose if the\ncode explains only where an object was constructed.\n\nEngineer's\n[maritime platform architecture case study](/portfolio/a-maritime-platform-built-in-clean-layers/)\ndescribes separating presentation, request handling and database-owned business\nlogic. It gives a context for deciding what a request handler should own. In\nthis illustrative design, the handler receives the boundary it calls and the\nwiring site chooses its implementation. The choice of where a rule is enforced\nis a separate decision that should follow the application and its data.\n\nIn a test, make the failure meaningful. Inject a store that refuses an operation\nbecause its conditions were violated and confirm that the caller handles the\ndocumented result. Pass a real adapter through the same contract to test the\ndeployment path. Agreeing on the shape of a function call is useful, and\nrepresentative failure cases are how the dependency's behavioural contract\nbecomes visible.\n\n## Where it goes wrong\n\nAn object can appear flexible while it reaches into a central registry to look\nup arbitrary services. Its constructor then says little about what it needs, and\na wiring error can surface only when a rarely used path first runs. Prefer to\nmake the needed collaborators visible at the boundary people instantiate. If a\nframework resolves them, give important startup checks a way to exercise the\ncomplete composition.\n\nConfiguration is another collaborator with lifecycle. Give the service its\nrequest deadline as part of its configuration when assembling the component.\nValidate that value when assembling the component and test the result with a\nboundary configuration. This makes a malformed setting visible during startup\nand gives a test a direct way to set the state it needs. Use configuration types\nthat make important units and defaults clear.\n\nA common lifecycle error stores a request-scoped collaborator in an object\nshared by many requests. A later call can use the wrong request state or a\nclosed resource. Review which component owns each resource and when the next\ncall can run. Test overlapping requests when lifetime influences correctness.\nKeep state passed explicitly through the operation when it belongs only to that\noperation.\n\nFinally, avoid abstractions that only repeat a stable API. Introduce a boundary\nwhen the component has a reason to choose an implementation, control lifetime or\nexercise an important contract. Keep its responsibilities small enough that the\nwiring remains readable. A good composition point gives maintainers a clear\naccount of where configuration becomes usable behaviour and where they can\nverify the result.\n\n## Further reading\n\n- [Microsoft .NET dependency injection](https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection).\n  Explains injection, scopes and service lifetimes.\n- [Spring dependencies and collaborators](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html).\n  Describes ways components declare their collaborators.\n- [Jakarta Dependency Injection](https://jakarta.ee/specifications/dependency-injection/2.0/).\n  Specifies injection annotations and scope concepts for Java.\n\n\u003chttps://engineer.company/glossary/dependency-injection/\u003e\n","date_modified":"2026-11-25T07:18:46Z","description":"Pass a clock and a store explicitly, choose their lifetimes and test a component without changing global state.","formats":{"gemtext":"https://engineer.company/glossary/dependency-injection/index.gmi","gopher":"https://engineer.company/glossary/dependency-injection/gophermap","html":"https://engineer.company/glossary/dependency-injection/","json":"https://engineer.company/glossary/dependency-injection/index.json","markdown":"https://engineer.company/glossary/dependency-injection/index.md","pdf":"https://engineer.company/glossary/dependency-injection/index.pdf"},"kind":"page","language":"en","title":"What is dependency injection?","url":"https://engineer.company/glossary/dependency-injection/","version":1}