Is it normal that the constructor of any class decorated with the controller decorator, is being called every request? What if I need to initialize some thing just once or play with some dependency just once? And what is the reason behind this behavior originally if it is intended?
Hello @m0uneer,
The controller is instantiated for each request. This is to manage concurrent access and avoid memory sharing problems if you ever wish to store data on the controller temporarily.
In this example we haven't an object to store data without memory sharing problem (if controller is a singleton):
@Controller('/path')
class MyCtrl {
private currentForm: MyFormModel;
@Post('/')
myMethod(@BodyParam() myModel: MyFormModel) {
this.currentForm = myModel;
// ... call async methods or other instruction based on currentForm
}
}
I know this example is a little absurd but if you have two or more concurrent access, you may have problems.
But I think in the most case, we don't need to create a controller for each request. Maybe we need to add an option / decorator to declare controller as Singleton.
See you
Hello, @Romakita
Yeah, a Singleton controller is the most common case and I think this should be the default behavior and you can add another on request decorator for sharing memory problems. But in my opinion, sharing memory should be a responsibility of the app owner because handling it with initiating the whole controller again and again comes with a cost in terms of performance.
I agree. I'll change that for the next version (v1.4) and add a decorator to specify if controller is Singleton or not.
v1.4.0-22 fix the controller instantiation :)
Great. Thanks Romakita :)