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! 💻✨

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay