DEV Community

Cover image for Exploring Scopes
Aarshdeep Singh Chadha
Aarshdeep Singh Chadha

Posted on

Exploring Scopes

๐Ÿ› ๏ธ I dove into creating a project that showcased the practical application of scopes. By walking through the project step by step, I was able to not only reinforce my own understanding but also provide a beginner-friendly explanation to help others grasp this concept.

The Book Definitions:

  • Scoped: Objects are created once per request or scope and reused within that scope, ensuring consistency and efficiency within a defined boundary.
  • Transient: Objects are created each time they are requested, ensuring freshness and avoiding unintended sharing of state across multiple clients.
  • Singleton: Objects are created only once throughout the application's lifecycle, providing a single shared instance globally, suitable for resources that are expensive to create or manage. And I won't waste much time but directly give you a small walk through the code... So I started creating an MVC Project took the HomeController and modified it which looks like below each Repository generates a Guid.

Image description

And the Program.cs

Image description

and the results were as below
The first time started the project.

Image description

Refreshing the page.

Image description

In Simple Terms,
Transient = New Service - every time requested.
Scoped = New Service - once per request.
Singleton = New Service - once per application lifetime.

Happy coding! ๐Ÿ’ปโœจ

Top comments (0)