Dependency injection in nodejs using fortjs

Ujjwal Gupta
fortjs
Published in
2 min readAug 16, 2019

Dependency injection is a design pattern which tells to provide dependency at run time rather than binding a class with dependency (basically writing code with less coupling). The dependency injection pattern is very useful when you are developing your application in TDD approach.

And frameworks which provides dependency injection makes things easy for you since you don’t need to care about management of the dependency. Some of the frameworks which provides dependency injection are : angular for front end, dotnet-core , fortjs for nodejs etc.

In this article i will talk about how we can do dependency injection in nodejs using fortjs framework.

FortJs is a Full stack mvc framework for nodejs which enables you to write code which is modular , secure and code written are pretty much beautiful & readable. I will recommend you to read any of the below articles to have a sense of how fortjs works -

FortJs provides two special decorators for dependency injection - Assign, Singleton.

  1. Assign - Assign decorator can be used to assign a value to a variable. The variable will be assigned with the provided value at run time.

e.g :

export class UserController extends Controller {

@Worker()
index(@Assign('hello world') value) {
console.log(value) // hello world
}
}

In the above example - index method will be called with value “hello world”. Since it is handled by framework, we can test our method by providing multiple value.

2. Singleton - Singleton is used to create a singleton of the provided class. This enables you to maintain a single object across the whole application. FortJs will create a single object & inject this object whenever required.

Let’s see an example -

export class UserController extends Controller {

constructor(@Singleton(UserService) service) {
super();
this.service = service;
}
}

You can take a look at rest api examples provided by fortjs - https://github.com/ujjwalguptaofficial/fortjs/tree/master/example/rest . In the example you can see - how dependency injection is being used for creating rest api and writing test codes.

Thanks for reading it guys, hope you have liked it. Don’t forget to hit the clap button 😬, if you liked it.

--

--

Ujjwal Gupta
fortjs
Editor for

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript