In this tutorial, you will learn how to use dependency injection with Umbraco 8. In Umbraco v8 the whole API model moved away from the older approach a lot of CMS systems used, a global singleton based static helper like this:
To a more testable and flexible solution via dependency injection. When you install Umbraco v8 you will get an IoC/DI container out the box so now there really are no excuses to use dependency injection within your custom code. As everything is pre-configured for you on installation, using dependency injection within v8 is really simple. Read on how to find out more.
The Dependency Injection Problem
As a contrived example, let's say you want to inject some custom code into a controller. Using this code:
When you try to inject the interface into the controller, like so:
The page would fail to load and an exception will be thrown. The exception message will be in the format of
System.InvalidOperationException: Unable to resolve type: ....
In this instance, the exception gets thrown because Umbraco does not know how to map
ICustomCode to the
CustomCode class. To fix this issue, you will need to tell Umbraco how this mapping should work. You need to register your dependency with the DI container.
In Umbraco V8 the concept of components was introduced. Components are the new way to hook into the Umbraco pipeline and register your own custom functionality. In this article, I'm only going to focus on the component to register custom dependencies. It is worth noting that this approach can be used for things like registering custom events etc...
The component that needs to be registered to do dependency injection within Umbraco is the
IUserComposer. To register your own dependencies, you will need to create a class that implements
IUserComposer. On initial-load Umbraco uses refection to check for any classes that implement
IUserComposer. If it finds any, it will run the class and register any dependencies within it. To get the example above to work the
ICustomCode needs to be registered.
The snippet above demonstrates everything you need to register your own custom dependencies. Happy coding!
Registering Normal Controller
Out of the box, any Umbraco controller you register with Umbraco will work with dependency injection. If you create your own controller that inherits from the normal MVC controller class, then this will also need registering. You can register them the same, as seen above.
Different Lifecycle Requests Explained
When registering your own custom dependency you should also be aware of the different lifecycle requests: