DEV Community

Cover image for Difference between AddScoped, AddTransient and AddSingleton in .netcore
Neer S
Neer S

Posted on

Difference between AddScoped, AddTransient and AddSingleton in .netcore

In .NET Core (now called .NET 5 and later), when you register services in the dependency injection (DI) container, you have different options for specifying how instances of those services are created and managed. The three main lifetime options are:

  1. Singleton: Only one instance of the service is created for the entire application, and it is reused for each request.
    services.AddSingleton();

  2. Scoped: A new instance of the service is created for each HTTP request within the scope of that request.
    services.AddScoped();

  3. Transient: A new instance of the service is created every time it is requested.
    services.AddTransient();

Additionally, there is also a method called TryAddSingleton. This method is similar to AddSingleton, but it only adds the service if it hasn't been registered before. This can be useful when you want to ensure that a particular service is only registered once.
services.AddTransient();

Here's a brief summary of each:

  • Singleton:
     - One instance for the entire application.
     - Shared across all requests.
     - Useful for stateless services or services that can be shared safely.

  • Scoped:
     - One instance per HTTP request.
     - Shared within the scope of an HTTP request.
     - Useful for services that need to maintain state within the context of a single request.

  • Transient:
     - A new instance every time it is requested.
     - No sharing between different parts of the application.
     - Useful for lightweight, stateless services.

  • TryAddSingleton:
     - Adds the service as a singleton if it hasn't been registered before.
     - Useful to avoid unintentional duplicate registrations.

Choosing the appropriate lifetime for your services depends on the specific requirements of your application and how you want instances of those services to be managed and shared.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

👋 Kindness is contagious

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

Okay