Sitecore Super Power Friendly Dependency Injection

Vincent Lui
2 min readMar 19, 2019

Sitecore Dependency Injection

As all of us seasoned Sitecore developers should be aware by now, Sitecore now ships with and utilises Microsoft.Extensions.DependencyInjection Out Of The Box as of 8.2. I will not go through how awesome this is, along with the theories of Inversion of Control, and the basic of how registrations are meant to be done.

Some really cool blog posts that have discussed this in detail already:

So why am I writing yet another blog post on Sitecore Dependency Injection ?

The Sitecore instance I am working with uses Glass Mapper with T4 Templates Code Generation. By default, the models that are generated include both an interface abstraction, as well as the concrete class itself. Due to this reason, any service operation with methods would use interfaces as parameters, like so:

The registration process can become very tedious, hence I am using some Reflection utilities to make this registration process simpler.

Extending on the ServiceCollectionExtensions.cs as used by the Habitat demo to register concrete classes to their default implemented interface :

This is one potential way to become super lazy and throw everything into the container.

Don’t forget to always check the registrations in https://<sitecore instance>/sitecore/admin/ShowServicesConfig.aspx

The above example can be very overkill. Please use it responsibly, rather, take the above as inspiration and extend to cover your specific scenarios to register your service configurators easier.

Please leave a comment if you like, dislike, agree or disagree with this approach.

--

--

Vincent Lui

Sitecore Technology MVP 2020–2023 | Solution Architect on Sitecore, Akamai, Microsoft Azure | Passionate on DevSecOps Lifecycle @ CPA Australia