What's the recommended way to register a SearchIndexClient into DI container? (let's say we only have a single index) Register it as singleton or transient?
2 Answers
The short answer is that you should register it as a singleton, as long as you make sure to avoid using properties and methods that aren't thread-safe. Most of them are thread-safe; just avoid setting mutable properties from multiple threads and you should be fine.
For a more in-depth discussion of why this is the recommended practice and how you can extend it for more complex scenarios, see this related question.
In an ASP.NET Core app, you can inject the client as follows.
Install the packages: Microsoft.Extensions.Azure, Azure.Search.Documents (this is the latest)
In the ConfigureServices
method in startup.cs
, register the client:
using Microsoft.Extensions.Azure;
public void ConfigureServices(IServiceCollection services)
{
services.AddAzureClients(builder =>
{
builder.AddSearchIndexClient(new
Uri("my resource url"), new
AzureKeyCredential("my resource key"));
});
services.AddControllers();
}
Now say you want to use the client in your controller, you can inject it like so:
public class MyApiController : ControllerBase
{
private readonly SearchIndexClient _searchIndexClient;
public MyApiController(SearchIndexClient searchIndexClient)
{
_searchIndexClient = searchIndexClient;
}
}
You may not want to put your credentials directly in ConfigureServices
though, in which case you could store them in appsettings.Development.json
(or appsettings.Production.json
):
"SearchDocument": {
"endpoint": "my resource url",
"credential": { "key": "my resource key" }
}
and do this in ConfigureServices
:
services.AddAzureClients(builder =>
{
builder.AddSearchIndexClient(
Configuration.GetSection("SearchDocument"));
});
Read more about Dependency injection with the Azure SDK for .NET.