README
Snake DI
Extremely minimal dependency injection container tool
Basic usage
Just install the library, import the reflect-metadata shim in your application's
entry point and then use the bootstrap
method to resolve the dependencies for a class:
It is important to note that the bootstrap
method creates an entirely new container using
the provided argument as the entry point, but does not allow manipulation of
what is inside the container. For manipulating the container, see the global container
section below.
// Somewhere in your application
import 'reflect-metadata';
// Where you want to resolve dependencies for a class
const instance = bootstrap<InjectedClass>(InjectedClass);
Injecting properties into classes
This library uses constructor dependency injection, which means you just have to pass the desired type into the properties in the constructor without actually defining them:
@Injectable()
class Something {
constructor (private other: Other) {}
get otherThings(): Other {
return this.other;
}
}
// And the Other class also needs to use the Injectable decorator
@Injectable()
class Other {}
And Something.otherThings
will return the instance of Other as desired.
Using the globally available Container
If you'd like to use a more common approach, there's also a globally available
Container
class with three static methods: set
, get
, and remove
, which
are self-explanatory.
The usage is simple:
// Sets some class inside the container
Container.set(SomeClass);
// Somewhere else in the application
const someClass = Container.get(SomeClass);
// If you wish to remove the reference to the class
Container.remove(SomeClass);
License
MIT