---
title: Dependency injection
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

When developing applications with Xperience, you may need to use service classes provided by the API. For example, services for managing users, handling digital marketing activities, and more.

To use a service, you first need to create a service instance. We recommend instantiating Xperience services via dependency injection.

> **Tip:** If you are not familiar with the dependency injection design pattern in general, we recommend that you learn about it first. For example, you can start with the [Dependency Injection](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection) article.

## Dependency injection design pattern

Dependency injection is a design pattern that is common to many programming languages and environments. Instead of instantiating a service instance inside a class constructor, you can pass the service instance into the constructor as a parameter. This way classes (e.g. controllers) do not need to obtain and configure the instance of a class they depend on.

The following code snippet shows a general example of the dependency injection design approach. The controller declares the service it needs in a [primary constructor](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/instance-constructors#primary-constructors), and the dependency injection [provider](#dependency-injection-providers) supplies the instance without the need to instantiate it explicitly. The class captures the constructor's parameters automatically, so you can reference them directly in the class body.

```csharp
using CMS.Activities;

using Microsoft.AspNetCore.Mvc;

public class AccountController(ICustomActivityLogger customActivityLogger) : Controller
{
    public IActionResult Register()
    {
        customActivityLogger.Log("myregistration", new CustomActivityData { ActivityTitle = "Registration" });

        return View();
    }
}
```

> **Tip:** **Read-only fields and classic constructors**
>
> Parameters of a primary constructor aren't read-only and can be reassigned anywhere in the class. To prevent that, capture the parameter in a readonly field initialized from it, for example `private readonly ICustomActivityLogger customActivityLogger = customActivityLogger;`.
>
> Use a classic constructor with `private readonly` fields when the class needs extra logic in the constructor body, such as validating a dependency or computing a derived field:
>
> ```csharp
> using System;
>
> using CMS.Activities;
>
> using Microsoft.AspNetCore.Mvc;
>
> public class AccountController : Controller
> {
>     private readonly ICustomActivityLogger customActivityLogger;
>
>     public AccountController(ICustomActivityLogger customActivityLogger)
>     {
>         ArgumentNullException.ThrowIfNull(customActivityLogger);
>
>         this.customActivityLogger = customActivityLogger;
>     }
>
>     public IActionResult Register()
>     {
>         customActivityLogger.Log("myregistration", new CustomActivityData { ActivityTitle = "Registration" });
>
>         return View();
>     }
> }
> ```

Developing applications with the dependency injection pattern in mind provides the following benefits:

- Less maintenance – changing object implementation is easier without strong coupling.
- Easier testing – application logic can be tested in isolation from its dependent objects.
- Loose coupling – classes are not directly dependent on one another.

## Dependency injection providers

ASP.NET Core Web applications come with a dependency injection provider developed by Microsoft. The provider is designed to serve the needs of the framework and most consumer applications. However, it can also be replaced with another third-party service container.

> **Note:** **Service container requirements**
>
> To be compatible with Xperience, third-party service containers must support the features available in the minimum .NET version specified in the [current system requirements](https://docs.kentico.com/documentation/developers-and-admins/installation/system-requirements.md), including [Keyed services](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?#keyed-services).

Xperience adds all of its services into the application's [IServiceCollection](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.iservicecollection) during the `IServiceCollection.AddKentico()` call (see [Configure new projects](https://docs.kentico.com/documentation/developers-and-admins/development/website-development-basics/configure-new-projects.md)). This approach is completely independent of the service provider used by the application.

For example, to substitute the default Microsoft service container with [Autofac](https://autofac.org/):

1. Add the **Autofac.Extensions.DependencyInjection** NuGet package to your project.
2. Call `IHostBuilder.UseServiceProviderFactory(new AutofacServiceProviderFactory())` when building the web application.

   ```csharp title="Program.cs"
   using Autofac;
   using Autofac.Extensions.DependencyInjection;

   using Microsoft.AspNetCore.Builder;

   var builder = WebApplication.CreateBuilder(args);

   builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

   // Registers services directly with Autofac
   builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder => containerBuilder.RegisterModule(new MyApplicationModule()));

   var app = builder.Build();
   ```

The application now uses Autofac for dependency resolution.
