Dependency injection is an important technique in application programming in general and in asp.net core in particular. Dependency injection helps reduce the dependence of classes on each other while initializing them.
After cloning this repository and installing Visual Studio enter the project's folder through the command line and type the following code to run the program:
dotnet run
- Transient services are created each time they are injected or requested.
- Scoped services are created per scope. In a web application, every web request creates a new separated service scope. That means scoped services are generally created per web request and they are destroyed after the request finalize. An HTTP is a stateless protocol therefore the values of form data would be available for the current request. it will refresh on every request of the same user/different user.
- Singleton services are created per DI container. Generally means that they are created only one time per application and then used for whole the application life time. So what should be a singleton? Singleton should be used in cases where limited resources are available. For example, we have a WebSocket connection. If a new socket is created in every request, socket (io) - our source Outgoing TCP connections are limited by port numbers ~ 65000 per IP- will run out over time and we cannot provide service. Instead, a socket pool is created and this socket pool is made singleton. When the call comes, a socket is given from this pool, and when the job is finished, it is thrown into the pool again.
- Register your services as transient wherever possible. Because it’s simple to design transient services. You generally don’t care about multi-threading and memory leaks and you know the service has a short life.
- Use scoped service lifetime carefully since it can be tricky if you create child service scopes or use these services from a non-web application.
- Use singleton lifetime carefully since then you need to deal with multi-threading and potential memory leak problems.
- Do not depend on a transient or scoped service from a singleton service. Because the transient service becomes a singleton instance when a singleton service injects it and that may cause problems if the transient service is not designed to support such a scenario. ASP.NET Core’s default DI container already throws exceptions in such cases.
- https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore
- https://www.tektutorialshub.com/asp-net-core/asp-net-core-dependency-injection-lifetime/
- https://stackoverflow.com/questions/46413431/what-is-the-difference-between-request-and-session-scope-in-spring