Engineer a dependency injection container upgrade enabling scopes, decorators, and test…
- User
Engineer a dependency injection container upgrade enabling scopes, decorators, and test overrides.
Assistant
Engineer a dependency injection container upgrade enabling scopes, decorators, and test overrides.
The user wants a Dependency Injection (DI) container with specific features:
I need to design an API and an implementation for this container.
Language Choice: TypeScript is a great fit for this because DI is heavily used in the Angular/NestJS ecosystem, and it allows for strong typing using generics and Reflect.metadata (though for a standalone example, a string/symbol token based approach is often more portable and easier to understand without setting up emit decorators in a sandbox). I'll stick to a simple, clean TypeScript implementation that doesn't necessarily rely on reflect-metadata to keep the example self-contained, or I can simulate a minimal token-based system.
Let's stick to a Token-based system (string or symbol) mapped to a Factory or Value.
Core Components:
Container: The main registry.Registration: Holds information about how to create a service.Scope: Enum or constants (SINGLETON, TRANSIENT, SCOPED).ResolutionContext: Tracks resolution path (for circular dependency checks) and manages scoped instances.Feature 1: Scopes
SINGLETON: One instance for the whole container lifetime.TRANSIENT: New instance every time.SCOPED: One instance per "scope". This usually implies a parent-child relationship or a specific context object (like an HTTP request). I'll need a createScope() method on the container that returns a "Scope" or "Child Container".Feature 2: Decorators
Interface A -> ConcreteA.Interface A.Interface A by resolving ConcreteA, then passing it to a DecoratorA factory, and returning DecoratorA.Token = Factory(Decorator)( Resolution of Token (Base) ).registerDecorator(Token, Factory).Feature 3: Test Overrides
container.override(Token, NewFactory).reset() method is also useful.Drafting the Architecture:
type Token = string | symbol | Function;
interface Registration {
factory: (c: Container) => any;
scope: Scope;
decorators: Array<(instance: any, c: Container) => any>; // Decorators wrap the instance
}
enum Scope {
Singleton,
Transient,
Scoped
}
Wait, decorators usually work by wrapping the interface.
If I have ILogger -> ConsoleLogger.
I add TimestampLogger (wraps ILogger).
When I ask for ILogger, I should get TimestampLogger(ConsoleLogger()).
If I have multiple decorators, say Timestamp and Filter:
Filter(Timestamp(ConsoleLogger())).
Implementation of decorator resolution:
ILogger is a singleton, the whole chain (Logger + Decorators) should effectively be a singleton.
So, the caching key is the Token.Refining the Decorator logic:
If I register:
Container.register('A', () => new A(), Singleton)
Container.registerDecorator('A', (a) => new DecoratorA(a))
When resolving 'A':
Wait, this is tricky if the base is Singleton but we want different decorators in different scopes?
Usually, DI decorators apply globally. Let's assume global application for simplicity, or allow registerDecorator to take a scope?
Let's stick to: The registration of Token defines the scope. The decorators are part of the construction of that Token.
Refining Scoped Logic:
I need a concept of a Scope object.
const scope = container.createScope();
scope.resolve(Token) -> checks scope's local cache. If not found, resolves (using container's factories), caches in scope, returns.
Test Overrides:
container.register('A', A) (Production)
container.register('A', MockA, { override: true }) (Test)
API Design:
const container = new DIContainer();
// Basic Registration
container.register('IUserRepo', { useClass: UserRepository, scope: Scope.Singleton });
container.register('IEmailService', { useFactory: (c) => new EmailService(), scope: Scope.Transient });
// Decorators
// Decorators wrap the resolved instance.
container.registerDecorator('IEmailService', (instance, c) => new LoggingEmailWrapper(instance));
// Scopes
const requestScope = container.createScope();
const repo = requestScope.resolve('IUserRepo');
// Testing
const testContainer = container.createTestContainer();
testContainer.override('IUserRepo', MockUserRepo);
Let's write the code.
I will implement a class DIContainer.
Scope Implementation:
A ContainerScope class.
It needs a reference to the parent container to access factories.
It has its own cache for Scoped items.
The Decorator Chain:
If I register A, then add decorator D1.
Resolution:
A maps to registration.
Registration has baseFactory and decoratorFactories.
Resolution logic:
Edge Case: What if the Decorator needs dependencies?
The factory signature should be (instanceToWrap, container) => newInstance.
Test Overrides:
Ideally, createTestContainer() creates a child container. The child container allows registering existing tokens without error, overwriting the lookup for that scope.
Let's structure the response:
I will use a "Fluent API" style or configuration objects? Configuration objects are clearer for complex options like scopes.
interface Provider {
token: Token;
useValue?: any;
useClass?: any;
useFactory?: (container: Container) => any;
scope?: Scope;
}
Decorator registration:
interface DecoratorProvider {
token: Token;
decorate: (instance: any, container: Container) => any;
}
Let's refine the Scope logic.
A container can have Singleton instances.
A Scope (created from container) handles Scoped instances.
Transient is always new.
Refined Resolution Algorithm:
resolve(token):
instance.
b. Reduce through Decorators -> finalInstance.
c. Store in relevant Cache.finalInstance.Wait, decorators and caching. If I cache the result of the base factory, I have the unwrapped object. If I cache the result of the fully decorated chain, I get the final object. Standard behavior (like .NET Core DI) implies the resolved service (interface) is what is cached. The decorator usually implements the same interface. So we cache the final result.
Self-Correction on Decorators:
If I resolve A, and it has decorators, A implies the fully constructed object.
So: Base(A) -> Decorator(Base(A)) -> Result. Cache Result.
The "Test Override" implementation:
Simply a method register(token, provider, options: { isOverride: boolean }).
Or a specific override(token, provider) method is cleaner.
Constructing the Code: I'll provide a robust TypeScript implementation.
Features to ensure:
resolve(token): T.dispose() method to the Scope.Code Structure:
enum Scope { Transient, Singleton, RequestScoped } // RequestScoped = Scoped
class DIContainer {
// registries...
register(config);
registerDecorator(config);
resolve(token);
createScope(); // Returns a ScopeContext
}
class ScopeContext {
// caches scoped items
resolve(token);
dispose();
}
Let's refine the decorator registration. It needs to be attached to a token.
container.registerDecorator(token, (instance) => new Wrapper(instance))
It accumulates. container.registerDecorator(token, d2).
Order: Base -> D1 -> D2.
Let's write the prompt response. I will structure it as:
One detail: How do we handle dependencies inside decorators?
The factory signature (instance, container) allows the decorator to pull other dependencies if needed (e.g., new LoggerWrapper(instance, container.resolve('Config'))).
Implementation details:
Map for registry.Symbol for internal cache keys to avoid collisions? Not needed if we just use the Token as key.Let's start generating the solution. I will emphasize clean code and comments explaining the "Engineering" decisions (e.g., why the decorator pattern is applied during the resolution phase).
Final check on "Test Overrides".
A common pattern is creating a "Test Container" that inherits from the main one.
const testContainer = mainContainer.createChild();
testContainer.register(..., { override: true })
This is safer than mutating the global container during tests. I will implement createChild which is effectively a sub-scope that allows registration overrides.
Actually, createChild is basically the "Scope" mechanism but with write access to the registry (overrides).
Let's stick to:
createScope() -> For runtime request scopes.createTestContainer() -> For testing (which is technically a child container with override capabilities).Wait, technically a Child Container is a Scope. I can unify them.
A Child Container inherits registrations. If I register a token in the Child, it overrides the parent for that Child.
This covers both "Scoped" (Child caches Scoped instances) and "Test Overrides" (Child re-registers a token).
Actually, simpler:
createScope() creates a context that shares the parent's registry but has its own Scoped cache.
For testing, we just allow container.register to accept an override flag or have a specific override method.
Or, const testContainer = new Container(); testContainer.import(mainContainer); testContainer.override(...).
Let's go with the createChild() pattern. It's the most robust.
const child = parent.createChild();
Actually, strictly speaking, if I re-register a Singleton in a Child, it should be a Singleton within that Child. But usually, Singletons are root-level. For Test Overrides, we usually mock Transient or Scoped services. Mocking a Singleton in a child scope is fine.
Okay, the plan is solid.
Container class.Scope enum.register, resolve, createScope (returns a ContainerScope).registerDecorator.resolve logic handles the chain: Registry Lookup -> Base Factory -> Decorator Chain -> Cache Check -> Return.Let's go.
Specific constraint checks:
createScope() and Scope.Request.registerDecorator wrapping the resolution.createChild() which allows masking parent registrations.I will write the code to be dependency-free (no reflect-metadata requirement) to ensure it runs anywhere, using string/symbol tokens for demonstration, but keeping it generic.
Code outline:
type Token = string | symbol;
type Factory = (c: Resolver) => any;
interface Registration {
factory: Factory;
scope: Scope;
decorators: Array<(instance: any, c: Resolver) => any>;
}
enum Scope { Singleton, Transient, Scoped }
class Container implements Resolver {
// ...
register(token, factory, scope);
registerDecorator(token, wrapper);
createScope(): ScopeContext;
resolve(token);
}
class ScopeContext implements Resolver {
// ...
resolve(token);
}
I need to handle the interface properly so createScope returns something that behaves like the container but manages its own Scoped cache.
Let's execute. This solution engineers a robust Dependency Injection (DI) Container in TypeScript. It is designed to be framework-agnostic and demonstrates the architecture of modern DI systems (like those in Angular or NestJS) but with a cleaner, centralized API.
It implements the three core requirements:
Singleton (global), Transient (new instance), and Scoped (context-aware, e.g., per HTTP request).The system consists of three main parts:
Container: The global registry. It holds the mappings from Tokens to Providers.ContainerScope: A context-aware resolver created from the Container. It handles Scoped lifecycles and ensures singletons are shared correctly.Provider Logic: Internal logic determining how to instantiate, cache, and decorate dependencies./**
* DEPENDENCY INJECTION CONTAINER UPGRADE
* Features: Scopes, Decorators, Test Overrides
*/
// --- 1. Type Definitions ---
type Token = string | symbol | Function;
type Factory = (context: ResolutionContext) => any;
enum Scope {
SINGLETON, // Shared globally
SCOPED, // Shared within a specific scope (e.g., Request)
TRANSIENT // Created anew every time
}
interface ProviderConfig {
token: Token;
factory: Factory;
scope: Scope;
// Decorators are factories that take the instance and return a wrapped version
decorators: Array<(instance: any, context: ResolutionContext) => any>;
}
// --- 2. Core Classes ---
/**
* Abstract context to ensure we can resolve dependencies recursively
* regardless of whether we are in the Root Container or a Child Scope.
*/
abstract class ResolutionContext {
abstract get(token: Token): any;
}
/**
* The Root Container.
* Holds the master registry of providers and singleton cache.
*/
class Container extends ResolutionContext {
private registry = new Map<Token, ProviderConfig>();
private singletonCache = new Map<Token, any>();
constructor() {
super();
}
/**
* Registers a dependency.
*/
public register(
token: Token,
factory: Factory,
scope: Scope = Scope.SINGLETON
): this {
this.registry.set(token, { token, factory, scope, decorators: [] });
return this;
}
/**
* Adds a decorator to an existing token.
* Decorators are applied in order (Outer <- Inner <- Instance).
*/
public addDecorator(
token: Token,
decorator: (instance: any, ctx: ResolutionContext) => any
): this {
const config = this.registry.get(token);
if (!config) throw new Error(`Token ${String(token)} not registered.`);
config.decorators.push(decorator);
return this;
}
/**
* Creates a new Scope (e.g., for an HTTP Request).
* This scope shares singletons with the root but has its own cache for Scoped providers.
*/
public createScope(): ContainerScope {
return new ContainerScope(this.registry, this.singletonCache);
}
/**
* Resolve a dependency from the Root context.
*/
public get(token: Token): any {
return this._resolveInternal(token, this.singletonCache);
}
/**
* Test Helper: Replaces a dependency factory entirely.
*/
public override(token: Token, mockFactory: Factory): this {
const existing = this.registry.get(token);
if (existing) {
existing.factory = mockFactory;
// Usually mocks are singletons in test runs, but we respect the existing scope or default to Singleton
this.singletonCache.delete(token); // Clear cache to force re-creation with mock
} else {
this.register(token, mockFactory, Scope.SINGLETON);
}
return this;
}
protected _resolveInternal(token: Token, scopeCache: Map<Token, any>): any {
const config = this.registry.get(token);
if (!config) throw new Error(`Token ${String(token)} not found in registry.`);
// 1. Check Caching Strategy
if (config.scope === Scope.SINGLETON && this.singletonCache.has(token)) {
return this.singletonCache.get(token);
}
if (config.scope === Scope.SCOPED && scopeCache.has(token)) {
return scopeCache.get(token);
}
// 2. Instantiate
// We pass 'this' as the resolution context so it can resolve nested dependencies
// Note: For Scoped resolution, we need to be careful here.
// If we are in the root 'get', we can't resolve Scoped dependencies properly without a Scope object.
// However, for simplicity of the root container, we treat it as the resolution context.
const instance = config.factory(this);
// 3. Apply Decorators
const finalInstance = config.decorators.reduce(
(acc, dec) => dec(acc, this),
instance
);
// 4. Cache
if (config.scope === Scope.SINGLETON) {
this.singletonCache.set(token, finalInstance);
} else if (config.scope === Scope.SCOPED) {
// If resolved via Root, scoped behaves like singleton (fallback)
scopeCache.set(token, finalInstance);
}
return finalInstance;
}
}
/**
* The Scoped Container (Child Scope).
* Used for specific contexts (e.g., a Request).
*/
class ContainerScope extends ResolutionContext {
private registry: Map<Token, ProviderConfig>;
private parentSingletons: Map<Token, any>;
private scopeCache = new Map<Token, any>();
constructor(
registry: Map<Token, ProviderConfig>,
parentSingletons: Map<Token, any>
) {
super();
this.registry = registry;
this.parentSingletons = parentSingletons;
}
public get(token: Token): any {
const config = this.registry.get(token);
if (!config) throw new Error(`Token ${String(token)} not found.`);
// 1. Singleton Check (Defer to parent cache)
if (config.scope === Scope.SINGLETON) {
if (this.parentSingletons.has(token)) {
return this.parentSingletons.get(token);
}
// If not in parent yet, we must create it.
// NOTE: In a real app, we'd delegate creation back to the parent
// to ensure thread safety/global locking.
// Here we simulate by creating and setting parent cache.
const instance = this._create(config);
this.parentSingletons.set(token, instance);
return instance;
}
// 2. Scoped Check (Check local cache)
if (config.scope === Scope.SCOPED && this.scopeCache.has(token)) {
return this.scopeCache.get(token);
}
// 3. Transient or New Scoped
const instance = this._create(config);
if (config.scope === Scope.SCOPED) {
this.scopeCache.set(token, instance);
}
return instance;
}
private _create(config: ProviderConfig): any {
// Instantiate base
const instance = config.factory(this);
// Apply decorators
return config.decorators.reduce(
(acc, dec) => dec(acc, this),
instance
);
}
}
// --- 3. Usage Examples & Tests ---
// Interfaces for clarity
interface IDatabase {
query(): string;
}
interface ILogger {
log(msg: string): void;
}
interface IUserService {
getUser(): string;
}
// Tokens
const DB = Symbol('IDatabase');
const LOG = Symbol('ILogger');
const USER_SVC = Symbol('IUserService');
// Setup Global Container
const appContainer = new Container();
// Register Logger (Singleton)
appContainer.register(LOG, () => ({
log: (msg) => console.log(`[LOG]: ${msg}`)
}), Scope.SINGLETON);
// Register Database (Scoped - imagine a transaction per request)
appContainer.register(DB, (ctx) => {
const logger = ctx.get(LOG);
logger.log('DB Created');
return { query: () => 'DATA_FROM_DB' };
}, Scope.SCOPED);
// Register User Service (Scoped, depends on DB)
appContainer.register(USER_SVC, (ctx) => {
const db = ctx.get(DB);
return { getUser: () => `User with ${db.query()}` };
}, Scope.SCOPED);
// --- Feature Demonstration ---
console.log("--- 1. Decorators ---");
// Add a decorator to the Database to intercept queries
appContainer.addDecorator(DB, (dbInstance, ctx) => {
const logger = ctx.get(LOG);
return {
...dbInstance,
query: () => {
logger.log('Query Intercepted!');
return dbInstance.query();
}
};
});
console.log("--- 2. Scopes ---");
// Create Request 1
const requestScope1 = appContainer.createScope();
const userSvc1 = requestScope1.get(USER_SVC);
console.log("Request 1:", userSvc1.getUser());
// Create Request 2
// Verify that Scoped dependencies are unique per scope
const requestScope2 = appContainer.createScope();
const userSvc2 = requestScope2.get(USER_SVC);
console.log("Request 2:", userSvc2.getUser());
console.log("--- 3. Test Overrides ---");
// Override Database for testing purposes
const mockDb = { query: () => 'MOCK_DATA' };
appContainer.override(DB, (ctx) => mockDb);
// Create a new scope AFTER override
const testScope = appContainer.createScope();
const userSvcTest = testScope.get(USER_SVC);
console.log("Test Scope:", userSvcTest.getUser());
Resolution Context Abstraction:
By making ResolutionContext a base class for both Container and ContainerScope, factories ((ctx) => ...) don't need to know if they are being resolved globally or within a request. They just ask the context for dependencies, and the context handles the caching logic correctly.
Scope Handling:
Container's map.ContainerScope's local map. If you resolve a Scoped dependency from the root Container directly (without createScope), it effectively behaves as a Singleton (standard behavior in most DI frameworks).Decorator Chain:
The addDecorator method pushes a function into an array. During _create, we use reduce to wrap the instance. This allows multiple decorators (e.g., Logging, then Caching) to be stacked.
Test Overrides:
The override method modifies the registry in place and clears the relevant cache. In a production scenario, you might instantiate a completely separate Container for testing to avoid polluting the global app state, but direct mutation is efficient for integration testing setups where you want to replace specific heavy services (like DB connections) with mocks.