How to use new instance for every new HTTP request in NestJS? The Next CEO of Stack OverflowHow can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?How to manage a redirect request after a jQuery Ajax callHTTP GET request in JavaScript?How is an HTTP POST request made in node.js?How can I add new array elements at the beginning of an array in Javascript?HTTP GET Request in Node.js ExpressAsync/Await Class ConstructorNestJS with TypeORM: When using custom repository, is a service needed anymore?How use external entities in nestjs project with typeorm?How to get multiple remote schemas stitched with Nestjs and apollo server

Should I tutor a student who I know has cheated on their homework?

Can a Bladesinger Wizard use Bladesong with a Hand Crossbow?

WOW air has ceased operation, can I get my tickets refunded?

Is a distribution that is normal, but highly skewed considered Gaussian?

Why didn't Khan get resurrected in the Genesis Explosion?

Why do airplanes bank sharply to the right after air-to-air refueling?

Why does standard notation not preserve intervals (visually)

Where do students learn to solve polynomial equations these days?

How to edit “Name” property in GCI output?

Is wanting to ask what to write an indication that you need to change your story?

How many extra stops do monopods offer for tele photographs?

Find non-case sensitive string in a mixed list of elements?

Why, when going from special to general relativity, do we just replace partial derivatives with covariant derivatives?

Is it okay to majorly distort historical facts while writing a fiction story?

Why the difference in type-inference over the as-pattern in two similar function definitions?

Why is my new battery behaving weirdly?

A Man With a Stainless Steel Endoskeleton (like The Terminator) Fighting Cloaked Aliens Only He Can See

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Method for adding error messages to a dictionary given a key

Grabbing quick drinks

Is French Guiana a (hard) EU border?

INSERT to a table from a database to other (same SQL Server) using Dynamic SQL



How to use new instance for every new HTTP request in NestJS?



The Next CEO of Stack OverflowHow can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?How to manage a redirect request after a jQuery Ajax callHTTP GET request in JavaScript?How is an HTTP POST request made in node.js?How can I add new array elements at the beginning of an array in Javascript?HTTP GET Request in Node.js ExpressAsync/Await Class ConstructorNestJS with TypeORM: When using custom repository, is a service needed anymore?How use external entities in nestjs project with typeorm?How to get multiple remote schemas stitched with Nestjs and apollo server










1















I have an API and was trying to send a request. That is working but I noticed that the classes were not destroyed after I received a response. I'm working with nestJS at the moment but nodeJS + expressJS also had this issue when I tried to test.



I'm using following code:



@Injectable()
export class UsersService
s = '';

constructor()

async findAll(): Promise<any>
this.s += ' haha ';
return await this.s;




This returned haha first time haha haha the second time and so on.



I'm not really sure if this is the desired behaviour or may have not configured properly, because I'm just learning nestJS now. I have previously worked with Zend Framework which did not show this behaviour.



Any guidance will be much appreciated.



Thank you.










share|improve this question



















  • 1





    By design, injectable instances are singletons just like in many IOC frameworks (Spring for instance). This is actually useful if you want to use some cache mechanisms. Why would you want otherwise? For which usecase?

    – zenbeni
    Mar 9 at 10:28















1















I have an API and was trying to send a request. That is working but I noticed that the classes were not destroyed after I received a response. I'm working with nestJS at the moment but nodeJS + expressJS also had this issue when I tried to test.



I'm using following code:



@Injectable()
export class UsersService
s = '';

constructor()

async findAll(): Promise<any>
this.s += ' haha ';
return await this.s;




This returned haha first time haha haha the second time and so on.



I'm not really sure if this is the desired behaviour or may have not configured properly, because I'm just learning nestJS now. I have previously worked with Zend Framework which did not show this behaviour.



Any guidance will be much appreciated.



Thank you.










share|improve this question



















  • 1





    By design, injectable instances are singletons just like in many IOC frameworks (Spring for instance). This is actually useful if you want to use some cache mechanisms. Why would you want otherwise? For which usecase?

    – zenbeni
    Mar 9 at 10:28













1












1








1








I have an API and was trying to send a request. That is working but I noticed that the classes were not destroyed after I received a response. I'm working with nestJS at the moment but nodeJS + expressJS also had this issue when I tried to test.



I'm using following code:



@Injectable()
export class UsersService
s = '';

constructor()

async findAll(): Promise<any>
this.s += ' haha ';
return await this.s;




This returned haha first time haha haha the second time and so on.



I'm not really sure if this is the desired behaviour or may have not configured properly, because I'm just learning nestJS now. I have previously worked with Zend Framework which did not show this behaviour.



Any guidance will be much appreciated.



Thank you.










share|improve this question
















I have an API and was trying to send a request. That is working but I noticed that the classes were not destroyed after I received a response. I'm working with nestJS at the moment but nodeJS + expressJS also had this issue when I tried to test.



I'm using following code:



@Injectable()
export class UsersService
s = '';

constructor()

async findAll(): Promise<any>
this.s += ' haha ';
return await this.s;




This returned haha first time haha haha the second time and so on.



I'm not really sure if this is the desired behaviour or may have not configured properly, because I'm just learning nestJS now. I have previously worked with Zend Framework which did not show this behaviour.



Any guidance will be much appreciated.



Thank you.







javascript node.js typescript express nestjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 16:20









Kim Kern

10.8k43352




10.8k43352










asked Mar 8 at 15:47









SanjuSanju

708628




708628







  • 1





    By design, injectable instances are singletons just like in many IOC frameworks (Spring for instance). This is actually useful if you want to use some cache mechanisms. Why would you want otherwise? For which usecase?

    – zenbeni
    Mar 9 at 10:28












  • 1





    By design, injectable instances are singletons just like in many IOC frameworks (Spring for instance). This is actually useful if you want to use some cache mechanisms. Why would you want otherwise? For which usecase?

    – zenbeni
    Mar 9 at 10:28







1




1





By design, injectable instances are singletons just like in many IOC frameworks (Spring for instance). This is actually useful if you want to use some cache mechanisms. Why would you want otherwise? For which usecase?

– zenbeni
Mar 9 at 10:28





By design, injectable instances are singletons just like in many IOC frameworks (Spring for instance). This is actually useful if you want to use some cache mechanisms. Why would you want otherwise? For which usecase?

– zenbeni
Mar 9 at 10:28












1 Answer
1






active

oldest

votes


















1














With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:




  • SINGLETON: Default behavior. One instance of your provider is used for the whole application


  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.


  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage



Either add it to the @Injectable() decorator:



@Injectable( scope: Scope.REQUEST )
export class UsersService


Or set it for custom providers in your module definition:




provide: 'CACHE_MANAGER',
useClass: CacheManager,
scope: Scope.TRANSIENT,




What you are looking for are request-scoped providers. They are not supported in nest v5, see this issue. As for now, all providers are singletons.



They were added with this pull request though and will be part of nest v6. With the new version, we will get transient and per-request scopes.






share|improve this answer

























  • Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

    – Sanju
    Mar 11 at 15:18






  • 1





    You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

    – Kim Kern
    Mar 11 at 15:21






  • 1





    Please, see my update :-)

    – Kim Kern
    Mar 18 at 21:50











  • Sure did! Thank you for the update! :-)

    – Sanju
    Mar 19 at 6:40











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066621%2fhow-to-use-new-instance-for-every-new-http-request-in-nestjs%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:




  • SINGLETON: Default behavior. One instance of your provider is used for the whole application


  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.


  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage



Either add it to the @Injectable() decorator:



@Injectable( scope: Scope.REQUEST )
export class UsersService


Or set it for custom providers in your module definition:




provide: 'CACHE_MANAGER',
useClass: CacheManager,
scope: Scope.TRANSIENT,




What you are looking for are request-scoped providers. They are not supported in nest v5, see this issue. As for now, all providers are singletons.



They were added with this pull request though and will be part of nest v6. With the new version, we will get transient and per-request scopes.






share|improve this answer

























  • Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

    – Sanju
    Mar 11 at 15:18






  • 1





    You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

    – Kim Kern
    Mar 11 at 15:21






  • 1





    Please, see my update :-)

    – Kim Kern
    Mar 18 at 21:50











  • Sure did! Thank you for the update! :-)

    – Sanju
    Mar 19 at 6:40















1














With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:




  • SINGLETON: Default behavior. One instance of your provider is used for the whole application


  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.


  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage



Either add it to the @Injectable() decorator:



@Injectable( scope: Scope.REQUEST )
export class UsersService


Or set it for custom providers in your module definition:




provide: 'CACHE_MANAGER',
useClass: CacheManager,
scope: Scope.TRANSIENT,




What you are looking for are request-scoped providers. They are not supported in nest v5, see this issue. As for now, all providers are singletons.



They were added with this pull request though and will be part of nest v6. With the new version, we will get transient and per-request scopes.






share|improve this answer

























  • Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

    – Sanju
    Mar 11 at 15:18






  • 1





    You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

    – Kim Kern
    Mar 11 at 15:21






  • 1





    Please, see my update :-)

    – Kim Kern
    Mar 18 at 21:50











  • Sure did! Thank you for the update! :-)

    – Sanju
    Mar 19 at 6:40













1












1








1







With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:




  • SINGLETON: Default behavior. One instance of your provider is used for the whole application


  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.


  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage



Either add it to the @Injectable() decorator:



@Injectable( scope: Scope.REQUEST )
export class UsersService


Or set it for custom providers in your module definition:




provide: 'CACHE_MANAGER',
useClass: CacheManager,
scope: Scope.TRANSIENT,




What you are looking for are request-scoped providers. They are not supported in nest v5, see this issue. As for now, all providers are singletons.



They were added with this pull request though and will be part of nest v6. With the new version, we will get transient and per-request scopes.






share|improve this answer















With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:




  • SINGLETON: Default behavior. One instance of your provider is used for the whole application


  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.


  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage



Either add it to the @Injectable() decorator:



@Injectable( scope: Scope.REQUEST )
export class UsersService


Or set it for custom providers in your module definition:




provide: 'CACHE_MANAGER',
useClass: CacheManager,
scope: Scope.TRANSIENT,




What you are looking for are request-scoped providers. They are not supported in nest v5, see this issue. As for now, all providers are singletons.



They were added with this pull request though and will be part of nest v6. With the new version, we will get transient and per-request scopes.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 18 at 21:47

























answered Mar 8 at 16:16









Kim KernKim Kern

10.8k43352




10.8k43352












  • Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

    – Sanju
    Mar 11 at 15:18






  • 1





    You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

    – Kim Kern
    Mar 11 at 15:21






  • 1





    Please, see my update :-)

    – Kim Kern
    Mar 18 at 21:50











  • Sure did! Thank you for the update! :-)

    – Sanju
    Mar 19 at 6:40

















  • Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

    – Sanju
    Mar 11 at 15:18






  • 1





    You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

    – Kim Kern
    Mar 11 at 15:21






  • 1





    Please, see my update :-)

    – Kim Kern
    Mar 18 at 21:50











  • Sure did! Thank you for the update! :-)

    – Sanju
    Mar 19 at 6:40
















Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

– Sanju
Mar 11 at 15:18





Is there any alternative you could suggest to achieve this behaviour until nest releases the feature?

– Sanju
Mar 11 at 15:18




1




1





You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

– Kim Kern
Mar 11 at 15:21





You can always instantiate a service yourself and not rely on dependency injection, e.g. directly in a route method: const requestScopedService = new MyService(databaseConnection);

– Kim Kern
Mar 11 at 15:21




1




1





Please, see my update :-)

– Kim Kern
Mar 18 at 21:50





Please, see my update :-)

– Kim Kern
Mar 18 at 21:50













Sure did! Thank you for the update! :-)

– Sanju
Mar 19 at 6:40





Sure did! Thank you for the update! :-)

– Sanju
Mar 19 at 6:40



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066621%2fhow-to-use-new-instance-for-every-new-http-request-in-nestjs%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page