Course contentsShow
← Node.js
Lesson 703 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Scoped Dependency Resolution

Create and destroy request-specific objects for tasks like temporary caching or logging.

In this lesson, you will learn how to create and manage request-specific objects that exist only for the duration of a single HTTP cycle.

The Problem: Global vs. Local

In many web applications, you might need an object—like a database transaction, a temporary logger, or a per-request cache—that is created when a request arrives and destroyed when the response is sent. If you rely on global variables or singleton services, you risk "leaking" data between users, where User A’s temporary cache accidentally stores information meant for User B.

The Solution: Scoped Containers

"Scoped Dependency Resolution" solves this by injecting a container into the request lifecycle. Every time a request hits your middleware, you initialize a fresh container. Any service requested during that specific cycle is instantiated within that container. Once the request finishes, the container—and all objects inside it—are cleared from memory.

Here is a conceptual illustration of how this looks in a typical middleware stack:

// Middleware to attach a scoped context
app.use((req, res, next) => {
  // Create a new container for this specific request
  req.container = new Container();
  
  // Register a temporary logger that knows which Request ID it belongs to
  req.container.register('logger', new RequestLogger(req.id));
  
  // Automatically clean up when the response finishes
  res.on('finish', () => req.container.dispose());
  
  next();
});

Why it Matters

When you use a scoped resolution, your business logic doesn't need to know about the request ID or the specific database transaction state. You simply ask the container for the logger, and it provides the instance tied to that specific request.

This approach is powerful because it ensures memory safety and isolation. By explicitly disposing of the container (or allowing it to be garbage collected) after the response is sent, you prevent memory bloat and ensure that no stale data persists. It turns "transient" objects into well-managed, predictable resources that are perfectly synced with the life of a request.

Key Takeaway: Scoped dependency resolution ensures that temporary objects are uniquely created for a single request and safely destroyed once the work is complete, preventing cross-user data leakage and memory clutter.