Dependency Injection
Dependency injection for TypeScript/JavaScript.
For further insights, read on.
Installation
To install this library use your favorite package manager. No additional steps are required to start using the library.
npm install @n7e/dependency-injection
This library is implemented in TypeScript but can be used with JavaScript without any additional steps.
Container
A dependency injection container has the ability to produce values and resolve any dependencies to that value in the process.
Container
is just an interface describing the functionality of a dependency
injection container. To create a container instance use a
container builder.
Resolving dependencies
Once dependencies are configured there are a couple of ways to resolve dependencies from the container.
Since type information is not available at runtime, dependencies are located by a unique identifier.
Produce
You can explicitly resolve a dependency by its unique identifier or any of the configured aliases.
const someClass = container.produce("someClass");
You can also check if the container is able to produce a given dependency.
if (container.canProduce("someClass")) {
// ...
}
Construct
The container is able to construct classes and will attempt to resolve any required constructor arguments.
const someClass = container.construct(SomeClass);
If the container is unable to resolve a required constructor argument an error will be thrown.
If an array of constructor arguments is passed to the construct()
method they
will have precedence when constructing the instance.
const someClass = container.construct(
SomeClass,
[
"first constructor argument",
"second constructor argument"
]
);
Invoke
The container is able to invoke functions and will attempt to resolve any
required function arguments. The return value of the invoke()
method is the
return value of the invoked function.
container.invoke(someClass => {
// ...
});
If the container is unable to resolve a required function argument an error will be thrown.
To invoke instance methods you can pass the instance as the second parameter.
const someClass = new SomeClass();
container.invoke(someClass.someMethod, someClass);
If an array of function arguments is passed to the invoke()
method they will
have precedence when invoking the function.
const someClass = container.invoke(
(firstValue, secondValue) => {
// ...
},
null,
[
"first value",
"second value"
]
);
If a function is explicitly bound there's no way to inspect the required
function arguments. So to invoke bound functions you can pass the original
function signature to the invoke()
method, and they will be resolved from that
signature.
function someFunction(someClass: SomeClass): void {
// ...
}
container.invoke(someFunction.bind(someContext), null, [], someFunction);
If trying to invoke a bound function without providing the original function signature an error will be thrown.
Decorator
When constructing classes or invoking functions/methods the container will attempt to resolve dependencies by matching them to the parameter names. This imposes a limit and may result in excessively long parameter names to keep the dependency identifiers unique.
To mitigate this you can use a decorator to define the identifier of the dependency to inject.
import { inject } from "@n7e/dependency-injection";
class SomeClass {
private readonly someOtherClass: SomeOtherClass;
public constructor(@inject("someOtherClass") someClass: SomeOtherClass) {
this.someOtherClass = someClass;
}
}
In the example above the dependency with an identifier matching "someOtherClass" will be used regardless of the name of the parameter.
Since this ties SomeClass
to the container this decorator should be used
sparingly
Container Builder
To create a container instance you should use a ContainerBuilder
. This gives
us an opportunity to configure any desired dependencies (more on this later).
containerBuilder.addClass("someClass", SomeClass);
Ones we have configured the dependencies we can create a container instance.
const container = containerBuilder.build();
The container instance can now be used to resolve dependencies (more on this later).
const someClass = container.produce("someClass");
ContainerBuilder
is just an interface describing the functionality of a
container builder. To create a container builder instance you need to reference
a specific implementation.
Configuring dependencies
Using the container builder allows us to configure the dependencies available to the final container instance. The container will then be able to produce and resolve any dependencies we've configured.
The return value of the addClass()
, addFactory()
and configure()
methods
is a dependency definition instance which can be used to further configure a
dependency.
Classes
The container is able to construct classes so to make a class instance available as a dependency we would add the class as a dependency.
containerBuilder.addClass("someClass", SomeClass);
An instance of that class can now be resolved by the container. Either directly or as a dependency to another class or function invokation (more on this later).
const someClass = container.produce("someClass");
container.invoke(someClass => {
// ...
});
The parameter name of the arrow function in the example above acts as the dependency identifier to resolve.
Factories
A dependency factory is simply a function invoked when a dependency needs to be resolved. The factory can return any desired value. The function is invoked by the container and any function parameters will be resolved by the container.
containerBuilder.addFactory("value", () => "some value");
The value of a dependency factory can now be resolved by the container.
const value = container.produce("value");
The following is possible but should be avoided since it could break dependency lifetime expectancy. This can be achieved by configuring the lifetime of the dependency instead (more on this later).
// This should probably be avoided.
const someClass = new SomeClass();
containerBuilder.addFactory("someClass", () => someClass);
Aliases
A dependency can have a set of aliases that identifies the dependency. Any alias can be used as an identifier for the dependency.
containerBuilder.addClass("someClass", SomeClass)
.addAlias("someAlias")
.addAlias("someOtherAlias");
The dependency can now be resolved as if the identifier was any of the aliases.
const someClass = container.produce("someAlias");
container.invoke(someOtherAlias => {
// ...
});
Any collisions of dependency identifiers or aliases will result in an error being thrown
Lifetime
A dependencies lifetime dictates when it's going to be constructed/created. Any violation of a dependencies lifetime (such as a singleton having a transient dependency) will result in an error being thrown.
Transient
Transient dependencies will be constructed/created everytime they are resolved. This is the default lifetime if not explicitly configured.
containerBuilder.addClass("someClass", SomeClass)
.makeTransient();
const someClassInstance = container.produce("someClass");
const someOtherClassInstance = container.produce("someClass");
// `someClassInstance` and `someOtherClassInstance` are two different instances
// of the class.
Scoped
Scoped dependencies will be constructed/created once per dependency scope.
Dependency scopes are controlled by the user of the container by invoking
beginScope()
.
containerBuilder.addClass("someClass", SomeClass)
.makeScoped();
const someClassInstance = container.produce("someClass");
const sameClassInstance = container.produce("someClass");
// `someClassInstance` and `sameClassInstance` refers to the same instance.
container.beginScope();
const someOtherClassInstance = container.produce("someClass");
// `someOtherClassInstance` refers to a new instance.
Singleton
Singleton dependencies are only created once per container instance.
containerBuilder.addClass("someClass", SomeClass)
.makeSingleton();
const someClassInstance = container.produce("someClass");
const sameClassInstance = container.produce("someClass");
// `someClassInstance` and `sameClassInstance` refers to the same instance.
container.beginScope();
const stillSameClassInstance = container.produce("someClass");
// `stillSameClassInstance` refers to the same instance as `someClassInstance`
// and `sameClassInstance`.
Default Container Builder
There's a provided default implementation of ContainerBuilder
ready to use.
import { DefaultContainerBuilder } from "@n7e/dependency-injection";
const containerBuilder = new DefaultContainerBuilder();
// Configure any desired dependencies.
const container = containerBuilder.build();
Scopes
Scopes are completely arbitrary and up to the user of a container to control. One common use case is to start a new scope for every incoming request when implementing an HTTP server.
container.beginScope();
After a new scope has been initiated any scoped dependencies will now once again be created when resolved.
Depending on a container
To avoid the common mistake of depending on a container instance we should try to explicitly declare the dependencies instead of depending on the container itself if possible.
Don't do this:
class SomeClass {
private readonly someOtherClass: SomeOtherClass;
public constructor(container: ContainerInterface) {
this.someOtherClass = container.produce("someOtherClass");
}
// ...
}
const someClass = new SomeClass(container);
Do this:
class SomeClass {
private readonly someOtherClass: SomeOtherClass;
public constructor(someOtherClass: SomeOtherClass) {
this.someOtherClass = someOtherClass;
}
// ...
}
const someClass = container.construct(SomeClass);
This makes the dependencies clear and the class more testable.