When to use Singleton vs Transient vs Request using Ninject and MongoDB

后端 未结 3 1934
南笙
南笙 2020-12-31 01:58

I\'m not quite sure when I should use SingletonScope() vs TransientScope() vs RequestScope() when I do my binding in my global.cs file.

I have for example my call to

3条回答
  •  轮回少年
    2020-12-31 02:21

    In general in a web app, you want state to be request scope as much as possible.

    Only in the case of very low level optimisations are you ever likely to run into a case where its appropriate to create singleton objects (and the chances even then are that you'll pull such caching / sharing logic out into another class which gets pulled in as a dependency on your other [request scope] objects and make that singleton scope). Remember that a singleton in the context of a web app means multiple threads using the same objects. This is rarely good news.

    On the same basis, transient scope is the most straightforward default (and that's why Ninject 2 makes it so) - request scope should only come into the equation when something needs to be shared for performance reasons, etc. (or because that's simply the context of the sharing [as mentioned in the other answer]).

提交回复
热议问题