A Microsoft SQL Server client that integrates with Aspire, including health checks, metrics and telemetry.
$ dotnet add package Aspire.Microsoft.Data.SqlClientRegisters 'Scoped' Microsoft.Data.SqlClient.SqlConnection factory in the DI container for connecting Azure SQL, MS SQL database. Enables health check and telemetry.
Install the Aspire SQL Server SqlClient library with NuGet:
dotnet add package Aspire.Microsoft.Data.SqlClient
In the AppHost.cs file of your project, call the AddSqlServerClient extension method to register a SqlConnection for use via the dependency injection container. The method takes a connection name parameter.
builder.AddSqlServerClient("sqldata");
You can then retrieve the SqlConnection instance using dependency injection. For example, to retrieve the connection from a Web API controller:
private readonly SqlConnection _connection;
public ProductsController(SqlConnection connection)
{
_connection = connection;
}
The Aspire SqlClient component provides multiple options to configure the SQL connection based on the requirements and conventions of your project.
When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling builder.AddSqlServerClient():
builder.AddSqlServerClient("myConnection");
And then the connection string will be retrieved from the ConnectionStrings configuration section:
{
"ConnectionStrings": {
"myConnection": "Data Source=myserver;Initial Catalog=master"
}
}
See the ConnectionString documentation for more information on how to format this connection string.
The Aspire SqlClient component supports Microsoft.Extensions.Configuration. It loads the MicrosoftDataSqlClientSettings from configuration by using the Aspire:Microsoft:Data:SqlClient key. Example appsettings.json that configures some of the options:
{
"Aspire": {
"Microsoft": {
"Data": {
"SqlClient": {
"DisableHealthChecks": false
}
}
}
}
}Also you can pass the Action<MicrosoftDataSqlClientSettings> configureSettings delegate to set up some or all the options inline, for example to disable health checks from code:
builder.AddSqlServerClient("sqldata", settings => settings.DisableHealthChecks = true);In your AppHost project, install the Aspire.Hosting.SqlServer library with NuGet:
dotnet add package Aspire.Hosting.SqlServerThen, in the AppHost.cs file of AppHost, register a SqlServer database and consume the connection using the following methods:
var sql = builder.AddSqlServer("sql").AddDatabase("sqldata");
var myService = builder.AddProject<Projects.MyService>()
.WithReference(sql);The WithReference method configures a connection in the MyService project named sqldata. In the Program.cs file of MyService, the sql connection can be consumed using:
builder.AddSqlServerClient("sqldata");