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

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived