Dependency Injection

Redakt CMS uses dependency injection throughout the Redakt system. Services are registered with the built-in .NET Core IoC container in the Microsoft.Extensions.DependencyInjection namespace.

Registering Redakt services

To make Redakt service registration simpler, you use the IRedaktBuilder interface in the Microsoft.Extensions.DependencyInjection namespace. All Redakt service registrations are done through extension methods on this interface. Every module contains an AddMyModule() type extension method that will add all required services for that module to the container.

You obtain a reference to the IRedaktBuilder interface through the AddRedakt extension method on the IServiceCollection interface. This is normally done in the ConfigureServices method of your project's Startup.cs file. If you've followed the getting started guide, your ConfigureServices method looks like this:

public void ConfigureServices(IServiceCollection services)
{
    // ... framework and other services

    services.AddRedakt(this.Configuration, builder =>
    {
        builder.AddLiteDbDataStore();
        builder.AddBackOffice();
    });
}

In this scenario, the LiteDB data store module and the Redakt back office module have been registered. You can add other modules in the same way, with a builder.AddMyModule() call (replace MyModule for the actual module name). The order of adding modules here is not important.

Injecting services

You can inject Redakt services into your own code at any place where services may be injected, like controllers, attributes, filters, etc. You will usually want to inject one of the following services.

IRedaktApplication

This is the interface for the main Redakt application class, part of the Redakt.Core namespace. It contains the services collection and global options. If you only need a single Redakt service, you can also inject just that service instead of the whole Redakt application instance.

IRedaktContext

For request-bound code, you can inject the IRedaktContext interface from the Redakt.Web namespace. This contains the current site object, page object, HTTP context, and helper methods. This is the interface you will normally want to inject into custom controllers, attributes and tag helpers. It is also passed as the model into all Razor page layouts.

Please note that modifying objects in the Redakt context during a request can lead to unexpected results and is generally not recommended.

Replacing the built-in container

The built-in container is normally adequate, but if you prefer a different (faster or more feature rich) container, a number of mainstream containers can be configured to replace the built-in .NET Core container. See the respective container's documentation for how to do this (some linked below).