The subscription_expiry function directly calls the current time, and testing began to show instability starting around midnight. To test date boundaries, the team introduced a large injection container, registering each class individually. In reality, this issue could be resolved more simply by using a clear clock parameter.
The core principle of dependency injection is to use code that explicitly declares its dependencies, rather than automatically finding or creating them. The container is simply a means of organization, not the end goal. Explicit dependencies make the call relationships clearer and also allow for better control over the conditions that actually affect the results, making testing more effective.
Minimum Dependencies: A Key Skill
type Clock = { now(): Date };
function isExpired(expiresAt: Date, clock: Clock): boolean {
return expiresAt.getTime() <= clock.now().getTime();
}
Create a real-time clock and test with a fixed time. The deadline boundary includes equal time intervals, and the rules are defined within the function. The test does not need to wait for the system time to elapse. This interface does not predict the number of clocks that will be needed in the future, but only expresses the current required capabilities.
Don’t pass the entire application context just to read a single timestamp. Passing a large context hides dependencies, making it easy for functions to access the database, logs, and configuration at any time. Testing also requires constructing large objects. Parameters should ideally reflect the actual usage range.
This example also reveals a common oversight: a single clock check should only be performed once. Suppose functions independently check for trial periods, grace periods, and paid subscriptions, each calling now(). This would result in inconsistent results when crossing boundaries. The caller can capture now at the beginning of the operation and pass it to multiple independent checks. Whether to maintain consistent timing within the operation is a business requirement, not determined by the injected framework.
Clock cannot handle all timing-related tasks. For tasks that require persistent absolute times, use a monotonic clock. Rename both to now(), and return a fixed number in the test, which will make the measurement logic appear easy to test but semantically incorrect. In addition to the small interface, the name should also clearly indicate the capabilities it provides.
Creating Objects in a Root Collection
The database client, email adapter, and business services are unifiedly assembled at the application entry point. Business functions only rely on the pre-constructed capabilities and do not create new connections internally based on environment variables. This ensures clear locations for connection lifecycle, configuration, and testing replacements.
Standalone applications can typically be organized using standard function factories. Containerization may reduce boilerplate code when dependencies are numerous, the scope is complex, or when a framework already provides a container. However, before adopting a container, it’s important to evaluate the costs associated with registration errors, runtime lookups, and debugging, rather than viewing containerization as a sign of a mature architecture.
The root configuration should not include business processes. It is responsible for connecting and managing the lifecycle, while payment rules remain at the domain or application level. Otherwise, if business logic is concentrated in the startup file, the structure becomes difficult to maintain.
A typical factory can express many wiring relationships:
- Validate configuration upon startup.
- Create a connection pool.
- Construct a payment adapter.
- Pass the required capabilities to the order service.
If the payment adapter needs to asynchronously read a key, it should first wait for it to complete before listening externally. Returning the ready and shutdown functions makes it clearer than letting the caller guess whether a particular constructor is still initializing in the background.
As dependencies expand, the benefits of containers primarily lie in achieving a unified scope, reducing redundant assembly, and integrating with frameworks. Before adopting a container, it’s important to identify potential pain points, such as:
- Do you have dozens of request scope objects?
- Do you need plugin discovery?
- Are you duplicating the same object graph in multiple places?
If you only have five standard services, tracking names, decorators, and reflection might be more difficult than explicitly passing parameters.
One principle remains after using containers: business code should not call the container. The container.resolve("mailer") is hidden within the payment function, and essentially acts as a service locator. The call signature no longer indicates dependencies. The container should remain at the boundary of the composition, and the business service still receives specific capabilities.
Design should be user-centric
The reporting service needs to read data and save results, without relying on a general repository containing dozens of methods. The narrow interface makes it easier for replacements, and also limits the service from using irrelevant capabilities.
However, creating interfaces for pure functions that only implement one specific way might simply increase navigation costs. It’s generally worthwhile to isolate things like time, randomness, persistence, networking, and expensive computations. A simple string formatting function doesn’t necessarily need to be injected.
Ideally, the interface should be driven by the specific use case, rather than a complete copy of a third-party SDK. Otherwise, upgrades from the vendor would propagate through all business code, and the test doubles would also need to simulate a large number of irrelevant methods. The adapter layer would then translate the vendor’s results into a stable, internal semantic representation.
Assume that the refund service only requires refund(paymentId, amount, idempotencyKey). The interface returns internal results such as “Completed”, “Processing”, or “Explicit Failure”, rather than transmitting the dozens of optional fields from the vendor’s response verbatim. Network timeouts cannot directly map to “Explicit Failure” because the refund may have already been executed. The interface must maintain a recovery path for “Uncertain Results” otherwise, simple boolean values in testing will mask the most dangerous scenarios in production.
It’s also important to clarify the concept of abstraction and belonging. The user decides what semantic meaning they need, and the adapter is responsible for providing it. There’s no need to force all business modules to rely on a single, all-encompassing Repository<T>. For example, order queries need to be able to read cancellable orders based on the tenant, while report queries need pagination projection. These two query capabilities can be different. Repeating a small number of type declarations is often more convenient than using a very broad interface.
Lifecycle Management Cannot Be Left to Chance
Connection pools should be reusable, and transaction objects should be limited to within a single transaction. The request context should not be a global singleton. If the dependency injection container is misconfigured, it can also lead to different users sharing states that should not be shared.
Regarding dependencies on blocking operations, the application should stop accepting new tasks, wait for the controlled operation to complete, and release resources when exiting. Tests should also close the connection to avoid the appearance of successful completion without actually terminating the process. The dependency design includes a lifecycle, not just constructor parameters.
Failure in asynchronous initialization requires clear communication. Do not initiate a background connection that cannot be waited for within the constructor, and then allow the service to accept requests before it is ready. You can use an asynchronous factory, or explicitly make the initialization process wait for readiness.
The most common form of scope errors is when a long-lived service holds a short-lived state. A singleton order service, for example, might receive a tenant context during its construction and continue to use that tenant for subsequent requests. The correct approach is typically to have a client that can be long-lived and re-used without any requests, explicitly passing the context when calling, or to create lightweight services within the request scope. It’s important not only to consider whether an object is thread-safe, but also to consider what data it holds and when that data is valid.
Dependency management, especially within localized scopes, requires careful attention. When using a callback within a transaction, the repository associated with that transaction connection should be created within the callback. After the callback completes, the repository reference should not be exported. If the closure saves the transaction repository in a singleton cache, and the types still match, the actual connection will have already been terminated. The type system alone cannot guarantee the lifecycle; structural constraints and integration testing must work together.
The order of shutdown is determined by the dependency direction. First, stop the new request, then wait for the controlled task, and finally close the client required by the business. If the database is closed first, the background queue will still attempt to write, but this is not a business rule issue, but rather a problem with the lifecycle contract of the assembly layer. Testing can record the shutdown call order, but the actual connection release still requires verification using a real client.
Testing Replacement Does Not Equal Production Interchangeability
A fixed clock is a reliable alternative because it requires minimal semantic overhead. However, an in-memory database may lack features such as transactions, constraints, and sorting, and therefore cannot be considered fully equivalent simply because it implements the same interface.
Conduct contract testing to verify the interactions between the storage and external adapters, ensuring that the expected behavior of the caller is realized in the actual implementation. The test doubles are only responsible for verifying the scope of the current test, and the critical persistence semantics still require verification through real integration.
Dependency injection should also prevent the arbitrary selection of unverified implementations. When configuring adapters, validation should be performed to ensure that only allowed values are used, and failures should occur during startup. Falling back to in-memory storage may make the system appear functional while losing data.
Contract testing should verify the semantic dependencies that the caller actually relies on, such as whether duplicate, idempotent keys return the same business result, whether a missing record results in a null value or an exception, and whether concurrent updates can be detected. It does not require replicating all of the vendor’s tests, but it must cover the states translated by the adapter. Test doubles can only implement these capabilities, and cannot be used as a substitute for “behavior consistency” instead of “interface consistency”.
It is also important to avoid making assertions that tie the number of internal calls to the implementation. A refund use case should demonstrate that repeated requests do not result in a second business refund, rather than asserting that the database method is called exactly twice. The latter would hinder caching, batch reads, and transaction reorganization, but it does not necessarily protect the business. Only the number of calls itself should be considered a core assertion, such as allowing external charging to call once.
A Refund Use Case: Only Inject the Capabilities It Truly Needs
The refund process requires reading the payment summary, creating a refund intent, calling the vendor, and saving the confirmation result. The interface can be designed around these actions, rather than receiving a database object containing all CRUD methods. The caller uses a stable payment identity and an idempotent intent, and the vendor adapter returns “completed,” “pending confirmation,” or “explicitly rejected.” This narrow capability makes test constructs smaller and prevents the refund process from arbitrarily modifying user data or other irrelevant states.
However, the interface must include a failure semantics. If a real supplier might submit a response and then lose it, the test double should always return a boolean, so the most dangerous branch is removed. The double must be able to generate pending confirmations and business tests must verify that it correctly saves and restores identities; the real adapter test must confirm how it identifies network uncertainty windows. Injection makes it easier to control conditions, and the test should not have the ability to create atomic operations that do not exist in production.
Whether a dependency requires injection can be determined by examining its source of change. Pure functions with clear inputs and outputs, such as currency rounding, can be easily injected. However, operations like network payments, clocks, random identifiers, and persistent storage can affect external state, requiring careful boundary management. Injecting all functions, on the other hand, makes the business logic overly reliant on factories and interfaces, obscuring the underlying process. Each abstraction should clearly state which replacement, lifecycle, or validation problem it solves.
Configuration, keys, and runtime identities should not be combined into a single context.
The configuration is validated at startup, and the keys are read from a controlled source. Tenants and operators provide the values on each call. These three types of values have different lifespans. A singleton service can hold immutable vendor configuration, but it cannot store the user identity from the initial request as an attribute and reuse it for subsequent requests. Even with a single-threaded Node.js application, asynchronous operations and scope issues can occur without requiring multithreading.
Key rotation also requires clarification on when the adapter should be refreshed. At startup, a fixed configuration might be suitable for certain systems, while runtime rotation may require controlled reconstruction or explicit credential provision. Business functions should not arbitrarily read environment variables to determine the current vendor each time, as this would lead to inconsistent behavior when attempting the same operation with different configurations. Operation logs should retain non-sensitive adapter versions and business identities, making it easier to determine which contract to use during recovery.
Passing an immutable context to a function does not automatically guarantee that the client objects within it are also immutable. TypeScript’s readonly typically restricts property reassignment, but does not prevent changes to the internal state of an object. Database pools and SDKs are inherently stateful resources; the key is to have clear ownership and concurrency contracts for that state. Don’t assume complete tenant isolation simply because you’ve used readonly in the context type.
If Asynchronous Initialization Fails, Resources Must Be Released
Create a log reporter, database pool, and vendor client using a combined root order. After a vendor initialization fails, the created resources should be stopped, leaving no reporter threads or connections. Responsibility for releasing resources should be recorded in reverse order, starting with the last created and ending with the first, or when a failure or exit occurs. When using an existing runtime resource management mechanism, follow its conventions and avoid creating complex containers. If the cleanup itself fails, visible diagnostics are needed, while retaining the original reason for the initial failure.
The shutdown function should have a clear and defined policy for repeated calls. If the framework can simultaneously send signals and perform teardown, the second shutdown should safely return or provide an interpretable result. A limited wait should be maintained between stopping the reception and forcibly exiting, and any external operations that are in progress should have persistent identities and recovery paths. Maintaining a process indefinitely is not a reliable exit strategy, and simply killing the process cannot replace business recovery.
“Startup readiness does not guarantee that all dependencies will remain healthy indefinitely. A connected database may later become disconnected, and the boundaries of the call still require error handling. Successful resolution of a container does not guarantee network availability. Health checks should also be performed based on responsibility, determining whether a new task can be accepted, whether a specific capability can be completed, and whether the process is simply running. Do not treat dependency injection as a reliability layer.”
Escaping Transaction Scope Using Structural Constraints
The repository created within a transaction callback is only used within that callback and returns the business result, not a connection or repository reference. Background tasks, delayed callbacks, and singleton caches cannot hold this object. Otherwise, after the callback completes, the remaining code will still be type-matched, but will use a connection that has already been committed or released. Structural constraints, code reviews, and real client testing work together to protect against this, and a standard interface cannot fully express the complete lifecycle of the resource.
If a process requires collaboration between multiple modules within a transaction, it must either explicitly accept the transaction scope or be organized by an existing work unit mechanism. It’s not acceptable for some storage systems to use transaction connections while others secretly obtain new connections from a global pool, and then claim that all operations are atomic. Integration testing, which injects failures midway, can confirm that real data is rolled back together, but it’s difficult to prove this with a memory surrogate.
Conducting a Practical Maintenance Experiment to Assess Container Profitability
Help new maintainers find the databases, email systems, and clocks used by the order service, modify a test dependency, and then track resource shutdowns. If a factory is easily visible and used infrequently, it doesn’t need to be migrated; if the framework provides clear scope and lifecycle, it’s usually more reasonable to continue using it. Choose based on actual navigation and assembly costs, rather than a technology being labeled as “enterprise-level.”
Even after introducing the container, integration tests using the root configuration can still verify the completeness of registration, the validity of configuration, and the correctness of the scope. Intentionally removing a key registration should fail during startup, and only report an error in the first payment request; intentionally registering a request as a singleton should be detected by concurrent tenant tests. The container does not reduce the verification requirements; it only changes the location of the connections.
When testing concurrent requests from two tenants, where one request pauses before the other completes, and then continues, it’s important to verify that each tenant uses the correct identity. If the two requests are executed sequentially, it may be difficult to observe the shared, mutable context. This experiment validates the scope semantics and doesn’t require simulating real network latency. Resource release should be verified separately using real clients to avoid one successful replacement handling all the proofs.
Review the code to see if it’s more honest.
A single test case could combine the following scenarios: Email service starts successfully, but database connection fails. The startup process should release any previously created email clients and stop providing external services, rather than leaving a partially initialized application. Then, execute the shutdown function twice to confirm that the repeated shutdown process is clear. An abnormal resource management path is often easier to expose design flaws than a successful connection.
The chosen implementation should also be observable at runtime. When configuring, the logging system should record the non-sensitive implementation name and version, but not the key values. This allows you to determine which implementation was used for a specific request during troubleshooting, without having to add environment-specific checks within the business logic. Connection information should be centralized at the startup point, while business logic-related decisions should be made at the point of use, with each having its own responsibility.
Regarding legacy code, it’s possible to initially wrap the existing global client with a thin adapter, and then gradually migrate dependencies to more complex modules. This avoids the need to rewrite all the relationships in a single modification. During the migration, it’s important to identify which paths still rely on global state, to prevent new and old client implementations from having different caches, connection pools, or transaction contexts. Introducing new dependencies is a controlled transformation, not just increasing the number of parameters.
When deciding whether to continue with an abstraction, compare it against a single real change. For example, switching email providers from vendor A to vendor B, if the changes are concentrated in the adapter and the root combination, then the boundary plays a role. Conversely, if all callers rely on vendor A’s error codes, then simply renaming the interface for the SDK is sufficient. However, if adding an interface to a pure calculation function does not reduce the scope of changes, then there is no need to maintain this abstraction.
Can the function signature reveal whether it depends on time, network, or a database? Can the test control the boundary without modifying the global state? Can the creation and closing of connections be pinpointed to specific locations? These questions are more meaningful than simply knowing how many services are registered.
It’s best to start by extracting a clock from a difficult-to-test function, and then call an external adapter to access it. Each level of abstraction should reduce the actual complexity. If you need to write more assertions to simulate internal steps after injection, the abstraction level might be too fine-grained, and you should consider merging the functionality again.
Dependency injection makes the system transparent about its dependencies. The best starting point is often not choosing a framework, but rather explicitly defining the external conditions that currently exist within a function but determine its behavior as parameters.
We can proceed gradually based on risk: first, isolate the clock and external dependencies, then clearly define the scope of resources, and finally, consider containers only when the complexity of the combination actually increases. At each step, maintain realistic implementations for testing, rather than replacing all dependencies with successful mock returns. This approach ensures that dependencies are not just for making tests pass easily, but rather for making them easier to understand and verify.