Introduction

In this article, I am going to present a complete tutorial how easily setup Dependency Injection using Inversion of Control container in Umbraco V7 solution. There are many .NET containers, but before we pick a specific one - it's worth visiting the IoC Battle page, where you can find a performance comparison of popular IoC frameworks. In this example, we will focus on Autofac. Once configured, we should be able to use Dependency Injection in both MVC and Web API controllers. Using this flexible technique, we are able to inject components such as services directly into controllers, but there are more advantages like:

Configuration flexibility

Loosely couple architecture

Testing using mock objects

Removing knowledge of a concrete implementations

Concurrent or independent development

In many cases our website should be able to integrate with other services – in some cases, we need to create REST endpoint to feed some data. This can be done in a very easy way using Umbraco.Web.WebApi.UmbracoApiController. This class wraps a classic WebApi engine and it’s possible to use Umbraco related objects and services. Our plan is to use the benefits of Dependency Injection in sample controllers.

After the process finishes, we are ready to use Autofac and set up the container – Umbraco application started event is the right place. RegisterIoCContainer() method wraps the logic of building the container.

WebModule is a custom class which is used to bundle up a set of related components into one logical unit – it’s flexible and recommended approach. In this case, we have only two components SampleService and UmbracoContext – but you can register as many as you want. Thanks to the last line, UmbracoContext.Current is available through Dependency Injection.

To create a view and show data from our ViewModel, we need to create document type, whose name corresponds to the name of the controller rendering the view. So let’s go to the backoffice and create a document type named “SampleRenderMvc” with a template. Then let’s create a custom class in “Controllers” folder named “SampleRenderMvcController”. After injecting ISampleService into local variable via constructor we are able to use ISampleService contract.

SampleRenderMvcController is ready, so let’s create a simple view based on ExtendedModel with items property. Go to Views folder and change view type from UmbracoTemplatePage to UmbracoViewPage. With UmbracoViewPage view, it is possible to iterate via custom model property and render the list.