Are you confused in AddTransient() and AddScoped()? In .NET Core DI?

Its really easy to get confused between AddTransient() and AddScoped() in .NET Core dependency injection. This confusion is completely normal because, at a high level, both seem to look same but behave the differently.

Its really easy to get confused between AddTransient() and AddScoped() in .NET Core dependency injection. This confusion is completely normal because, at a high level, both seem to look same but behave the differently.

-> Let me explain this with simple example. Lets say, I am making an API request to get user details. Request flow will be like this:

1. A request to API endpoint -> /api/user/getuser/{slug}
2. The UserController & GetUser got called.
3. Inside the controller, two services are used:
3.1  UserProfileService
3.2 UserNotificationService
4. Both services depend on the same UserRepository to read the basic profile details and notification configuration from the database.

-> Now let’s see what happens with different lifetimes.

1. AddTransient()
1. Consider if UserRepository is registered as AddTransient() lifetime in program.cs:
2. The request comes in
3. The UserController is created
4. UserProfileService is created → new UserRepository instance is created
5. Next, UserNotificationService is created → another new UserRepository instance is created.

Conclusion - So within a single HTTP request, two separate repository objects are created. This is fine for small, stateless logic, but it can be inefficient for database access.

2. AddScoped()
1. Now consider if UserRepository is registered as AddScoped() lifetime in program.cs:
2. The request comes in
3. The UserController is created
4. UserProfileService is created → UserRepository instance is created
5. UserNotificationService is created → the same UserRepository instance is reused.

Conclusion - So within one HTTP request, only one repository object exists, and both services share it.

In real production systems, AddScoped() is usually the great choice for repositories, especially when working with databases or DbContext, because it keeps data consistent and avoids unnecessary object creation.

I hope this simple flow-based explanation clears your confusion with dependency injection in .NET Core.


Notice Inappropriate?

If you come across any inappropriate content, please report it to our administrators!

Leave a Reply

Please login to post comments.