IoC Container for Typescript - 3.X
This is a lightweight annotation-based dependency injection container for typescript.
It can be used on browser, on react native or on node.js server code.
The documentation for the previous version can be found here
Table of Contents
- IoC Container for Typescript
- Basic Usage
- The Container Class
- A note about classes and interfaces
- Browser usage
- Migrating from previous version
This library only works with typescript. Ensure it is installed:
npm install typescript -g
To install typescript-ioc:
npm install typescript-ioc
Typescript-ioc requires the following TypeScript compilation options in your tsconfig.json file:
That's it. You can just call now:
And the dependencies will be resolved.
You can also inject constructor parameters, like:
and then, if you make an injection to this class, like...
The container will create an instance of PersonService that receives the PersonDAO from the container on its constructor. But you can still call:
And pass your own instance of PersonDAO to PersonService.
Note that any type with a constructor can be injected.
You don't have to do anything special to work with sub-types.
The above example will work as expected.
You can use scopes to manage your instances. We have three pre defined scopes (
Scope.Local), but you can define your own custom Scope.
Allow just one instance for each type bound to this scope.
So, we can create a lot of PersonController instances, but all of them will share the same singleton instance of PersonService
Types bound to this scope will share instances between the same build context. When you call
Container.get, a new build context is created and every container resolution performed will share this context.
In that example, we can expect:
The container will create a new instance every time it will be asked to retrieve objects for types bound to the Local scope.
The Local scope is the default scope. So you don't need to configure nothing to work with a Local scope. However if you have a Type bound to other scope and want to change it to the Local scope, you can use the
To define a new scope, you just have to extend the Scope abstract class:
Factories can be used to create the instances inside the IoC Container.
The Factory method will receive the
BuildContext as parameter. So, if you need to retrieve another instance from the container to perform the factory instantiation, you can ask it to the BuildContext. For example:
The @OnlyInstantiableByContainer annotation
The @OnlyInstantiableByContainer annotation transforms the annotated class, changing its constructor. So, it will only be able to create new instances for the decorated class through to the IoC Container.
It is usefull, for example, to avoid direct instantiation of Singletons.
If anybody try to invoke:
Will prodeuce a TypeError.
The Container class
You can also bind types directly to Container resolution.
// it will override any annotation configurationContainer.bindPersonDAO.toProgrammerDAO.scopeScope.Local;// that will make any injection to Date to return// the same instance, created when the first call is executed.Container.bindDate.toDate.scopeScope.Singleton;// it will ask the IoC Container to retrieve the instance.;
Container.bindPersonDAO;;// or;// personDAO.personRestProxy is defined. It was resolved by Container.
; // throws a TypeError. classes decorated with @OnlyInstantiableByContainer can not be instantiated directly;Container.bindPersonDAO.factorypersonFactory; //Works OK; // Works OK
@InjectValue decorator and Constants
It is possible to bind constants to the Container. It is useful for configurations, for example.
And then you can use the
@InjectValue decorator exactly as you use
@Inject to inject instances.
It is possible to inject an internal property from a constant, like:
And also to mix constants and other container injections, like:
Value Injections can be used direclty in class properties:
Or read directly from the Container:
It is possible to bind an internal property of a constant, like:
It is possible to create specific namespaces with custom configurations and then tell container to use these namespaces.
Only if the namespace
'test' is active, the
'config.dependencyURL' will resolve to
To use the default namespace, just call
If you want to remove a namespace, just call
It is not possible to remove the default namespace.
An alias called
'environment' is defined for the namespace method:
Container.namespace'test';Container.environment'test'; // both commands are equivalents
Take a look at here for more examples of namespaces usage.
Creating temporary configurations
You can use snapshot for testing or where you need to temporarily override a binding.
describe'Test Service with Mocks',;
Importing configurations from external file
You can put all manual container configurations in an external file and then use the '''Container.configure''' method to import them.
For example, you can create the
And then import the configurations using:
You need to load the configurations only once, but before you try to use the objects that depends on these files.
You can create configurations for specific namespaces, like:
A note about classes and interfaces
Typescript interfaces only exist at development time, to ensure type checking. When compiled, they do not generate runtime code. This ensures good performance, but also means that is not possible to use interfaces as the type of a property being injected. There is no runtime information that could allow any reflection on interface type. Take a look at https://github.com/Microsoft/TypeScript/issues/3628 for more information about this.
So, this is not supported:
Container.bindPersonDAO.toProgrammerDAO; // NOT SUPPORTED
However there is no reason for panic. Typescript classes are much more than classes. It could have the same behavior that interfaces on other languages.
So it is possible to define an abstract class and then implement it as we do with interfaces:
Container.bindPersonDAO.toProgrammerDAO; // It works
The abstract class in this example has exactly the same semantic that the typescript interface on the previous example. The only difference is that it generates type information into the runtime code, making possible to implement some reflection on it.
Using Container for testing
Some examples of using the container for tests:
or you can configure all your mocks togheter in a mocks.config.ts
and then in your test files:
or if you want to use the configurations and restore the container after the test:
Define configurations on a file, like
And then import the configurations using:
;;Container.configureconfig;// Then activate the environment calling the containerContainer.environmentprocess.env.NODE_ENV;
It was tested with browserify and webpack, but it should work with any other similar tool.
- Circular injections are not supported
Migrating from previous version
Some breaking changes:
This library does not support old ES5 code anymore. So, you need to change the target compilation of your code to
es6 (or anything else newer, like es2016, es2020, esnext etc)
tsconfig.json needs to include at least:
This decision was taken to help to solve a lot of bugs with react native and browser environments.
If you need to support es5 code, you can keep using the 1.2.6 version
A lot of confusion with
@AutoWired motivated us to rename it to
@OnlyInstantiableByContainer. It is a big name, but it says exactly what that decorator does. It is completely optional (The container will always work in the same way when instrumenting the types), but it transforms the decorated constructor to avoid that anybody create new instances calling direct a new expression.
So you need to change all references to
@Provided @Provides and Provider interface removed
We changed the name of the interface
ObjectFactory and also change the definition of this type to be a simple function signature.
So, now we have:
// previous version;// new version;
Following the same design, whe renamed the
// previous version// new version
@Provides decorator was removed because it could cause a lot of problems, once it was used in the class that would provide an implementation, that usually was always defined in different files. That forced us to had things like
ContainerConfig.addSource() to scan folders for files. It caused problems in react native, in browser and in some environments like lambda functions.
We redesigned a new way to load container configurations that does not need to scan folders anymore, removing the problems and improving the performance. Take a look at
Container.configure method for a better option for the old
We had a minor change in the Snapshot handling. We don't have anymore the public method
Container.restore(type). A safer way to work with snapshots was implemented. Now the
Container.snapshot method returns a snapshot object. That object has a
The new way: