2-Transient
ASP.NET Core will create and share an instance of the service every time to the application when we ask for it. The service can be added as Transient using the AddTransient method of IServiceCollection. This lifetime can be used in stateless service. It is a way to add lightweight service.
Example:
3-Scoped
ASP.NET Core will create and share an instance of the service per request to the application. It means that a single instance of service is available per request. It will create a new instance in the new request. The service can be added as scoped using an AddScoped method of IServiceCollection. We need to take care while the service registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like a singleton object.
Example:
Answer in Hindi:
ASP.NET Core MVC mein, ek registered service ka service lifetime nirdharit karne ke liye aapko Dependency Injection container ka istemal karna hota hai. Yahan par main aapko kuch kadam bataunga jo aapko ek seva ki service lifetime nirdharit karne mein madadgar saabit ho sakte hain.
Maan lijiye ki aapko ek service ko Transient, Scoped, ya Singleton lifetime mein register karna hai. Yahan main inn teeno cases ke liye kuch code snippets provide kar raha hoon:
1-Transient:
Har baar jab seva ki zaroorat ho, ek naya instance bana diya jayega.
2-Scoped:
Ek hi instance ko ek request ya scope ke andar share kiya jayega. Aksar web applications mein yeh ek HTTP request ke andar ek hi instance ko refer karta hai.
3-Singleton:
Ek hi instance ko poore application ki jindagi mein share kiya jayega.
About Author
Brijesh Kumar
Database Developer
I have more then 6 years Experience in Microsoft Technologies - SQL Server Database, ETL
Azure Cloud - Azure SQL Database, CosmosDB, Azure Data Factory, PowerBI, Web Job, Azure Function, Azure Storage, Web Apps, Powershall
and Database Migration On-Premise to Azure Cloud.
LinkedIn : https://www.linkedin.com