Dependency injection in .NET has become fairly commonplace and there are many popular frameworks out there to do so. If you’re embracing the philosophy of building generic re-usable pieces of functionality, you may not want to tie yourself down to one particular technology. Fortunately Sitecore provides a solution that will allow you to easily use different IoC frameworks between projects. This post will describe how to utilize the Sitecore configuration factory for basic dependency injection.
Through the use of patch files Sitecore will allow you to define objects that will be available at runtime. These nodes are defined under /configuration/sitecore and can be retrieved using the Sitecore API. Let’s begin by creating creating a class that will be injected into a controller we have set up.
As you can see from above, TestController.cs has a dependency on IInjectedClass.cs. Instead of using a third party DI framework, we are using the Sitecore configuration factory to create the object in the constructor. Our injected class is defined as an XML node in the config file above. Line 11 of TestController.cs demonstrates how to use the configuration factory to create our object. The boolean parameter specifies whether an exception is thrown if the path you specified cannot be found in the Sitecore patch file.
- True will throw an exception if the path does not exist
- False will not throw an exception and null will be returned.
What if our InjectedClass also had a dependency that needed to be resolved? No problem!
We treat the new dependency that InjectedClass has just like we did in our TestController, adding a line to our config and creating the object in our constructor. Now when TestController attempts to create the InjectedClass object, an instance of InjectedClassDependency will be created as well.
Still have questions? Want more complex usages of the Sitecore configuration factory? Leave me a comment or check out the Sitecore Community Docs for more information