API Reference / API Methods / ASP.NET
Jun. 24, 2019

In this tutorial we are going to explore how to easily add the Algolia library to your ASP.NET applications.

ASP.NET MVC/Web API

Add the Algolia library to your project.

1
dotnet add package Algolia.Search

Inject a reusable client

In order to keep performance optimal, we don’t want to create an instance of a client every request. To address this, we will 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"));
    ...
}

As a client is thread-safe you can use a SearchClient for multiple indices. You don’t have to create on client per index.

If you are using other clients such as AnalyticsClient or InsightsClient you should also add them as singleton in the service provider.

Reusable client in your controllers

Then, to reuse the SearchClient instance in your controllers, you have to 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;
    }
}

Did you find this page helpful?

.NET