Skip to main content

Inject reusable clients

To maintain optimal performance, reuse the SearchClient instance for all requests. To do this, register it as a singleton in the service provider. In the Startup.cs file, add the following lines to the ConfigureServices method:
C#
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<ISearchClient, SearchClient>();
    services.AddSingleton<ISearchClient>(new SearchClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY"));
    // ...
}
For ASP.NET minimal APIs, add the following line to your Program.cs file:
C#
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<ISearchClient>(new SearchClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY"));
The SearchClient class is thread-safe, so you can reuse the same client with multiple indices.
Also register other clients, such as AnalyticsClient and InsightsClient, as singletons in the service provider.

Add reusable clients to controllers

To reuse the SearchClient instance in your controllers, add the following lines:
C#
public class HomeController : Controller
{
    private readonly ISearchClient _searchClient;

    public HomeController(ISearchClient searchClient)
    {
        _searchClient = searchClient;
    }
}
I