Skip to main content

Sitecore

Dependency Injection in Sitecore

Istock 1394630019

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

Transient is registered as below, they are created each time they are requested.

Transient

Scoped

Scoped is registered as below, they are created for each request, and disposed of after request.

Scoped

In Sitecore by default scoped behaves as Singleton, we need to set it in web.config as below:

Scoped Settings

Singleton

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.

Singleton

Hope that the above blog will help you to decide the lifetime of your services in Sitecore.

Happy Coding 😊

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Aditi Paliwal

Aditi has been with Perficient for over nine years and is a Technical Architect. She has more than 12 years of experience in .Net, which includes over nine years in Sitecore and is Sitecore 9 certified.

More from this Author

Follow Us