Dependency injection (DI) is a technique for achieving loose coupling between objects and their dependencies.
Rather than creating classes of classes or using static references to perform their actions, most classes declare their depending on a constructor.
Sitecore uses Construction injection and Sitecore implementation is based on Microsoft.Extensions.DependencyInjection.
Sitecore dependency injection implements the three lifetimes of services as the ASP.NET Core, below are three lifetimes of Services and how we can register them through code:
Transient is registered as below, they are created each time they are requested.
XM Cloud Roadmap Guide
XM Cloud is the future of enterprise content management offerings. The new sites, pages, and components tools offer an efficient content author experience that is not available with other CMS systems.
Scoped is registered as below, they are created for each request, and disposed of after request.
In Sitecore by default scoped behaves as Singleton, we need to set it in web.config as below:
Singleton is registered as below, and they are created the first time services are requested, every subsequent request uses the same instance and will only be disposed of once the application shuts down.
Hope that the above blog will help you to decide the lifetime of your services in Sitecore.
Happy Coding 😊