Exploring Scopes

midnightasc

Aarshdeep Singh Chadha

Posted on February 11, 2024

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! ๐Ÿ’ปโœจ

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
midnightasc
Aarshdeep Singh Chadha

Posted on February 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Exploring Scopes
webdev Exploring Scopes

February 11, 2024

ยฉ TheLazy.dev

About