Skip to main content
All docs
V24.1

Register Services in the Dependency Injection Container

  • 2 minutes to read

Register services required for your Controller in the dependency injection container. For this purpose, use IServiceCollection.

ASP.NET Core Blazor

Use the services parameter of the Startup.ConfigureServices method in the YourApplicationName.Blazor.Server\Startup.cs file:

public void ConfigureServices(IServiceCollection services) { 
//... 
  services.AddSingleton<IServiceOne, ConcreteServiceOne>(); 
  services.AddTransient<IServiceTwo, ConcreteServiceTwo>(); 
//...
} 
Windows Forms

To access the collection, use the Services property of the application builder object. The WinApplication.CreateBuilder method creates this object in the YourApplicationName.Win\Startup.cs file:

var builder = WinApplication.CreateBuilder(); 
builder.Services.AddSingleton<IServiceOne, ConcreteServiceOne>(); 
builder.Services.AddTransient<IServiceTwo, ConcreteServiceTwo>(); 

Access Services Using XafApplication

You can use XafApplication.ServiceProvider property to obtain services from a built-in service container. The following code sample demonstrates how to access ICaptionHelperProvider:

public class YourViewController : ViewController {
    protected override void OnActivated() {
        base.OnActivated();
        var caption = Application.ServiceProvider.GetService<ICaptionHelperProvider>().GetCaptionHelper().GetActionCaption("SaveAndNew");
    }
}

For information about access to services in Business Objects, refer to the following topic: Write Business Object Code that Accesses Services (Use Session or IObjectSpace).

Dependency Injection with Third-party Inversion of Control (IoC) Service Containers

In XAF Blazor, Web API Service, and Windows Forms .NET applications, you can register your favorite .NET IoC library instead of Microsoft’s IServiceProvider. For this purpose, you can call the UseServiceProviderFactory extension method of the application builder class.

var builder = WinApplication.CreateBuilder();
builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// OR
// builder.UseServiceProviderFactory(new DryIoCServiceProviderFactory());
See Also