Performance
To optimize performance of Algolia’s API client in your ASP.NET applications, it’s best to reuse the client instance whenever possible.
Inject a reusable client
To keep performance optimal, you should reuse the client instance for every request.
To do this, inject the SearchClient
as singleton
in the service provider.
Open the Startup.cs
file and add the following line in the ConfigureSerivces
method.
1
2
3
4
5
6
7
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton<ISearchClient, SearchClient>();
services.AddSingleton<ISearchClient>(new SearchClient("YourApplicationID", "YourSearchOnlyAPIKey"));
// ...
}
If you have a minimal API, you can add the following line to the Program.cs
file.
1
2
3
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ISearchClient>(new SearchClient("YourApplicationID", "YourSearchOnlyAPIKey"));
You can reuse the same SearchClient
for multiple indices,
as SearchClient
is thread-safe.
If you are using other clients such as the AnalyticsClient
or InsightsClient
also add them as singletons in the service provider.
Reusable clients in your controllers
To reuse the SearchClient
instance in your controllers, add the following lines:
1
2
3
4
5
6
7
8
9
public class HomeController : Controller
{
private readonly ISearchClient _searchClient;
public HomeController(ISearchClient searchClient)
{
_searchClient = searchClient;
}
}