From C# generics and Microsoft's Dependency Injection to a scope-based, type-safe DI system for TypeScript.
Two backend developers meet TypeScript
Both John (SvS-JohnC) and I started our professional journeys primarily as backend developers, working extensively with C# and the .NET ecosystem.
Over the years, we gradually became full-stack developers. And, as the old joke goes, one of the worst things that can happen to a frontend application is a backend developer deciding to build its UI.
Well, we were those backend developers.
But we had one particular interest that made our journey into frontend development a little different: we love generics and abstractions.
And when I say we love generics, I really mean it.
We've worked with complicated generic abstractions in backend applications and even experimented with them in game development using Unity. Classes with ten generic parameters? We've seen those. Sometimes, we were the ones writing them.
Not because complexity is inherently good, but because we enjoy exploring what a language's type system can express.
Then, on one of our projects, we were essentially forced to learn React.
And that's when we discovered TypeScript.
Another creation from Microsoft, but with a surprisingly different approach to its type system.
Conditional types, mapped types, literal types, generic inference, type transformations - compared with C#, TypeScript offered some fascinating possibilities.
Of course, it also had one significant limitation: all that beautiful type information disappears at runtime.
But this wasn't exactly new to us. John also had experience with Java and its generics, so the concept of type erasure was already familiar.
We knew its limitations, but we also understood its advantages. Having a powerful compile-time type system doesn't necessarily mean carrying all that information into runtime.
And TypeScript took compile-time type manipulation considerably further than we were used to.
Rather than seeing type erasure as an obstacle, we became curious about just how much we could achieve with TypeScript's type system alone.
In fact, we'd previously discussed ideas for our own programming language, combining a strict runtime type system with expressive abstractions. Some of the features we imagined were surprisingly close to what TypeScript could already express.
But that's another story.
The important part is that we didn't simply learn TypeScript because we had to. We genuinely started enjoying frontend development.
And eventually, having worked closely with both ecosystems, we began comparing their approaches to familiar architectural problems.
One of those problems was dependency injection.
Inspired by Microsoft's Dependency Injection
If you've worked with ASP.NET Core, you're probably familiar with Microsoft's dependency injection system.
We certainly were.
And we genuinely love it.
It's a great example of pragmatic engineering: relatively simple abstractions, predictable lifetimes, automatic resource management, and a feature set that keeps improving without introducing unnecessary complexity.
In the JavaScript ecosystem, there are plenty of DI libraries too, each with its own approach. Some rely on decorators and reflection metadata, while others take advantage of TypeScript's type inference.
We wanted to build something inspired by Microsoft's DI philosophy, but designed specifically for TypeScript.
John has always been particularly good at challenging existing designs and coming up with interesting architectural ideas.
We spent quite a bit of time brainstorming how a TypeScript DI system could work, questioning familiar abstractions and exploring different approaches.
Those discussions eventually became the foundation of Scope DI.
One particular question from those discussions became the foundation of the entire project.
What if everything were a scope?
In Microsoft's DI, we're used to several abstractions:
-
IServiceProvider- resolves dependencies. -
IServiceScope- represents a scope and its lifetime. -
IServiceScopeFactory- creates scopes.
We understand why these interfaces are separated. Smaller abstractions provide flexibility, replaceability, and freedom to evolve different responsibilities independently.
But we started wondering whether all three concepts could naturally be represented by one entity.
A scope.
A scope can resolve dependencies, own their instances and lifetimes, and create child scopes.
Why not make it the fundamental runtime building block of the entire DI system?
This also allowed us to represent dependency injection as an explicit hierarchy.
Every scope is a node in that hierarchy, and applications can have multiple independent roots.
Unlike Microsoft DI's flat scope model, where creating a scope from another scope doesn't establish nested ownership, our hierarchy explicitly represents parent-child relationships.
And that led naturally to our lifetime model:
| Lifetime | Behavior |
|---|---|
| Singleton | One instance owned by the root scope |
| Scoped | One instance per scope |
| ScopedInherited | Reuse an existing instance from an ancestor scope, or create one in the current scope |
| Transient | Create a new instance per resolution |
Disposable transient instances are also tracked by their owning scope for cleanup.
Dependency lifetimes could now be explained through scope ownership and instance reuse, rather than treating them as unrelated behaviors.
Two main abstractions
Of course, scopes still need to know which dependencies are registered and how they should be created.
That's where our second abstraction comes in.
We ended up with two main runtime abstractions:
Scope - responsible for resolution, instance ownership, lifetimes, disposal, and creating child scopes.
Dependencies Registry - the immutable metadata describing registered dependencies and their behavior.
All scopes within a hierarchy share the same registry instance. Different root hierarchies have independent registries.
Here's what the complete model looks like:
Dependencies Registry A (shared, immutable)
|
+-- Root Scope A
|
+-- Child Scope A1
| |
| +-- Grandchild Scope A1.1
|
+-- Child Scope A2
Dependencies Registry B (shared, immutable)
|
+-- Root Scope B
|
+-- Child Scope B1
The registry isn't part of the lifetime hierarchy. It describes dependencies, while the scopes manage their runtime instances.
And since every child scope shares the same registration information, its type remains consistent with its parent:
createChildScope(): DiScope<T_RegisteredDependencies>;
We also noticed how naturally hierarchical scopes could fit JavaScript applications - DOM trees, nested components, React providers, and so on.
That eventually led to our React integration, but that's another story.
For now, we had our architectural foundation.
And the name practically suggested itself.
Scope DI.
Registration decides, resolution follows
There was another important principle we borrowed from Microsoft's DI: dependency resolution should not make registration decisions.
We wanted registration to be the single source of truth.
If a dependency wasn't registered, it shouldn't be resolved. No implicit class instantiation, no automatic fallback, and no additional construction decisions made during resolution.
Registration defines which dependencies exist, which abstractions they expose, how they're constructed, and which lifetimes they follow.
The consumer should simply ask for a dependency.
We also wanted the dependency registry to remain immutable after building, following the same general philosophy as Microsoft's DI.
Configuration and execution should be separate phases.
During configuration, the builder accumulates dependency registrations. Calling build() produces a root scope with a finalized registry, which is then shared across its child scopes.
Scopes still manage mutable runtime state, but registration metadata remains fixed.
Registration defines what can be injected and how. Resolution simply follows those rules.
And that raised another interesting question.
If registration defines everything about a dependency, why shouldn't TypeScript know that information too?
Making TypeScript understand our dependencies
Our next goal was straightforward:
If we register a dependency under a key, TypeScript should know what we'll get when resolving that key.
No explicit result types at every resolution. No casts. No decorators or reflect-metadata.
Consider:
import { configureRootScope } from "@svs-tm/scope-di";
const scope = configureRootScope()
.map("mode")
.asValue("production")
.map("environment")
.asValue<string>("production")
.build();
const mode = scope.resolve("mode");
// ^? "production"
const environment = scope.resolve("environment");
// ^? string
// Compile-time error: this key was never registered.
scope.resolve("unknown");
TypeScript knows the registered keys and their result types. We can preserve precise literal types or explicitly widen them to abstractions when needed.
Even better, IntelliSense suggests available keys while configuring or resolving dependencies.
But how does the compiler know all this?
Carrying registrations through a generic type
We decided to accumulate registration metadata inside a generic type associated with the builder: T_RegisteredDependencies.
Each registration carries its dependency type and descriptor kind:
type DependencyMetadata<T_Dependency, T_DependencyDescriptorType extends DependencyDescriptorType> =
{
type: T_DependencyDescriptorType;
dependency: T_Dependency;
};
Registrations are grouped by keys, with tuples preserving the metadata of dependencies registered under each key.
Every time a dependency is registered, our AddDependency utility updates the builder's generic type. It replaces the metadata collection associated with that key, prepending the new registration while preserving the previous ones.
The result is a type-level representation of the registry that evolves with every registration.
By the time we call build(), TypeScript already knows which keys are available and what they resolve to.
The resulting scope retains that information through its own generic type, while the runtime registry contains the actual dependency descriptors.
No runtime reflection required.
Registering under abstractions
Of course, consumers shouldn't necessarily depend on concrete implementations.
import { configureRootScope, DependencyLifetime } from "@svs-tm/scope-di";
interface ILogger
{
log(message: string): void;
}
class ConsoleLogger implements ILogger
{
public log(message: string): void
{
console.log(message);
}
}
const scope = configureRootScope()
.map("logger")
.asClass<ILogger>(ConsoleLogger, DependencyLifetime.Singleton)
.build();
const logger = scope.resolve("logger");
// ^? ILogger
The registration exposes ILogger, while the actual implementation is ConsoleLogger.
The registration determines the abstraction consumers receive.
The caller doesn't select an implementation or specify an arbitrary result type. The compiler follows the contract established during registration.
Inferring dependencies without decorators
Now, what if one dependency requires another?
const scope = configureRootScope()
.map("logger")
.asValue<ILogger>(console)
.map("prefix")
.asValue("[Scope DI]")
.map("logMessage")
.asDependent("logger", "prefix")
.factory
(
(logger, prefix) => (message: string) =>
{
logger.log(`${prefix} ${message}`);
},
DependencyLifetime.Singleton
)
.build();
const logMessage = scope.resolve("logMessage");
// ^? (message: string) => void
logMessage("Hello!");
Notice that we never specified the types of logger or prefix inside the factory.
TypeScript inferred them from the registered keys passed to asDependent().
Internally, we use a mapped tuple type to turn the requested dependency keys into their corresponding result types:
type ResolvedDependencies
<
T_RegisteredDependencies extends RegisteredDependencies,
T_Keys extends DependencyResolutionKey<DependencyMappingKey<T_RegisteredDependencies>>[]
>
=
{
[T_Index in keyof T_Keys]: ResolutionResult<T_RegisteredDependencies, T_Keys[T_Index]>;
};
The same mechanism lets TypeScript check constructor compatibility and provide IntelliSense suggestions for available dependencies.
And the factory's return type becomes another registered dependency that subsequent registrations can use.
No runtime parameter reflection needed.
Collections: one key, multiple registrations
Eventually, we wanted to support multiple registrations under the same key.
But how should we distinguish resolving a single dependency from resolving the entire collection?
John came up with a particularly elegant idea.
Use a string key for singular resolution and a tuple containing that string for collection resolution.
const scope = configureRootScope()
.map("middleware")
.asValue("auth")
.map("middleware")
.asValue("logging")
.map("middleware")
.asValue("metrics")
.build();
const latest = scope.resolve("middleware");
// ^? "metrics"
const all = scope.resolve(["middleware"]);
// ^? ["metrics", "logging", "auth"]
That's it.
No separate collection namespace, special prefix, or additional resolution API.
Our registration metadata already preserves all dependencies registered under a key, with newer registrations inserted at the beginning.
Singular resolution uses the first entry. Collection resolution transforms the entire metadata tuple into a tuple of dependency types.
The key distinction is expressed with:
type DependenciesCollectionResolutionKey<T_DependencyMappingKey extends AllowedDependencyKey> =
[T_DependencyMappingKey];
type DependencyResolutionKey<T_DependencyMappingKey extends AllowedDependencyKey> =
T_DependencyMappingKey | DependenciesCollectionResolutionKey<T_DependencyMappingKey>;
The actual ResolutionResult type uses conditional types to distinguish between the two forms.
Because the metadata preserves registration order, TypeScript can infer the precise collection tuple.
It was one of those ideas that felt almost too simple after we implemented it.
And it fit naturally into the type system we'd already built.
What about asynchronous dependencies?
JavaScript introduces another challenge: asynchronous dependency creation.
We wanted asynchronous factories to be first-class citizens without sacrificing type safety.
const scope = configureRootScope()
.map("config")
.asFactoryAsync
(
async () => ({ apiUrl: "https://api.example.com" }),
DependencyLifetime.Singleton
)
.build();
const pendingConfig = scope.resolve("config");
// ^? Promise<{ readonly apiUrl: "https://api.example.com" }>
const config = await scope.resolveAsync("config");
// ^? { readonly apiUrl: "https://api.example.com" }
An important detail is that we don't determine asynchronous behavior simply by checking whether a result is a Promise.
Our registration metadata also tracks the descriptor kind: Value, Class, Factory, ClassAsync, or FactoryAsync.
A synchronous registration may intentionally contain a Promise as its value. That's different from an asynchronous factory managed by the container.
The descriptor metadata lets TypeScript distinguish those cases and determine how dependent factories, constructors, and collections should behave during asynchronous resolution.
We also introduced BoxedPromiseDependency to account for JavaScript's automatic promise assimilation when a synchronous dependency intentionally holds a Promise.
The important part is that TypeScript understands not only what a dependency is, but also how it was registered.
Lifetimes and disposal
One more aspect of Microsoft's DI philosophy was especially important to us: dependency ownership.
A DI system shouldn't merely create instances. It should also manage their cleanup, including transient dependencies.
class Connection implements Disposable
{
public [Symbol.dispose](): void
{
console.log("Connection disposed");
}
}
const rootScope = configureRootScope()
.map("connection")
.asClass(Connection, DependencyLifetime.Transient)
.build();
const childScope = rootScope.createChildScope();
const first = childScope.resolve("connection");
const second = childScope.resolve("connection");
// Two different instances.
childScope[Symbol.dispose]();
// Both instances are disposed.
Every transient resolution creates a new instance, but its owning scope tracks it for disposal.
We also support both synchronous and asynchronous scope disposal through Symbol.dispose and Symbol.asyncDispose.
We went slightly further by allowing synchronous disposal to initiate cleanup for asynchronously disposable dependencies as well.
Naturally, synchronous disposal cannot await that work, so deterministic asynchronous cleanup still requires Symbol.asyncDispose.
This was another deliberate balance between predictable ownership and API ergonomics.
And it follows the same fundamental idea: a scope owns the dependencies associated with its lifetime.
Where it all led
What started as a discussion between two .NET developers gradually became a complete dependency injection library.
We weren't trying to reinvent DI or prove that existing solutions were wrong.
We wanted to take the engineering philosophy we admired in Microsoft's DI, rethink a few abstractions, and explore what we could achieve with TypeScript's type system.
That led us to a few principles:
- Scopes are the fundamental runtime building blocks. They resolve dependencies, own instances, and create child scopes.
- The registry is shared and immutable. Every scope in a hierarchy follows the same registration metadata.
- Registration defines the contract. Consumers don't decide how dependencies are constructed.
- TypeScript knows the registrations. Keys, abstractions, collections, and asynchronous behavior are represented at compile time.
- Scopes manage lifetimes. Instance creation, reuse, inheritance, and disposal follow the scope hierarchy.
Not every decision was obvious from the beginning. Some ideas evolved, others required compromises, and a few led us into technical problems we hadn't anticipated.
But the fundamental concept remained the same.
The scope is the building block of the dependency injection hierarchy, backed by a shared, immutable registry.
That's how Scope DI came to life.
And once we had a working implementation, another question appeared:
How fast could we make it?
We started with straightforward optimizations, eliminating repeated lookups and moving decisions from resolution time to build time.
Later, things became considerably more interesting when we started exploring JavaScript engine optimization behavior.
But that's a story for the next articles.
This article is based on Scope DI, an open-source TypeScript dependency injection library I developed with architectural ideas and contributions from John (SvS-JohnC). The repository contains the implementation and more complete examples.
Top comments (0)