- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the AddSingleton vs AddScoped vs Add Transient C# Asp.net Core?
There are three ways by which dependencies can be registered in Startup.cs. i.e. AddSingleton, AddScoped and AddTransient.
Add Singleton
When we register a type as singleton, only one instance is available throughout the application and for every request.
It is similar to having a static object.
The instance is created for the first request and the same is available throughout the application and for each subsequent requests.
public void ConfigureServices(IServiceCollection services){ services.AddSingleton<ILog,Logger>() }
Add Scoped
When we register a type as Scoped, one instance is available throughout the application per request. When a new request comes in, the new instance is created. Add scoped specifies that a single object is available per request.
public void ConfigureServices(IServiceCollection services){ services.AddScoped<ILog,Logger>() }
Add Transient
When we register a type as Transient, every time a new instance is created. Transient creates new instance for every service/ controller as well as for every request and every user.
public void ConfigureServices(IServiceCollection services){ services.AddTransient<ILog,Logger>() }
Parameter | Add Singleton | Add Scoped | Add Transient |
---|---|---|---|
Instance | Same each request/ each user. | One per request. | Different for everytime. |
Disposed | App shutdown | End of request | End of request |
Used in | When Singleton implementation is required. | Applications which have different behavior per user. | Light weight and stateless services. |