What is Dependency Injection?
Dependency Injection is a software design pattern that will allow developers to develop loosely coupled codes between two components. It allows better management for future changes.
Along with better management, it allows for a better unit testing process and increases code reusability and maintainability.
There are a few ways of implementing DI.
- Constructor Injection: This injector supplies the dependency through the constructor of the class.
- Property Injection: The injector supplies dependency through the setter of the property of the class. As this is being done through Setter, this is also called Setter Injections.
- Method Injection: Over here client class implements an interface that declares the method to supply the dependency and using this interface the injector supplies the dependency to the client class.
In Sitecore, we will design with constructor injection.
To start off, create your project (either Foundation or Feature) in Solution.
Create a new interface and write down the methods you need. After that, add your concrete class and implement the interface.
Let’s say we are working on the article section of a project and this is a feature of articles and we need a repository to save articles.
Model
namespace Feature.Articles.Models
{
public class Article
{
public string Subject { get; set; }
public string Body { get; set; }
public List<string> AttachementList { get; set; }
public string Username { get; set; }
public List<string> Tags { get; set; }
}
}
Interface
public interface ISaveArticleReository
{
bool SaveArticle(Article article);
}
Class
public class SaveArticleRepository : ISaveArticleReository
{
public bool SaveArticleInSQLServer(Article article)
{
// do your code for saving in SQL Server
}
}
public class SaveArticleRepository : ISaveArticleReository
{
public bool SaveArticleInMongoDB(Article article)
{
// do your code for saving in Mongo DB
}
}
Set up the connection between the Interface and class.
You need to connect both the class and interface in the RegisterDependencies class. For the same, create a folder named DependencyInjection and create a class. Make sure the class is implemented from the interface. ISaveArticleReository.
Within the configure method, connect the class to the interface using three methods.

Join the conversation! Your thoughts help the community grow.