# Connect to RavenDB

<Badge text="⭐ Community Toolkit" variant="tip" size="large" />

<Image
  src={ravendbIcon}
  alt="RavenDB logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

This page describes how consuming apps connect to a RavenDB resource that's already modeled in your AppHost. For the AppHost API surface — adding a RavenDB server, databases, data volumes, secured instances, and more — see [RavenDB Hosting integration](../ravendb-host/).

When you reference a RavenDB resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire RavenDB client integration for automatic dependency injection, health checks, and telemetry.

## Connection properties

Aspire exposes each property as an environment variable named `[RESOURCE]_[PROPERTY]`. For instance, the `Uri` property of a resource called `ravendb` becomes `RAVENDB_URI`.

### RavenDB server resource

The RavenDB server resource exposes the following connection properties:

| Property Name | Description |
| ------------- | ----------- |
| `Host`        | The hostname or IP address of the RavenDB server |
| `Port`        | The port number the RavenDB server is listening on (8080 for HTTP, 443 for HTTPS) |
| `Uri`         | The server URI, with the format `http://{Host}:{Port}` or `https://{Host}:{Port}` |

**Example connection string:**

```
Uri: http://localhost:8080
```

### RavenDB database resource

The RavenDB database resource inherits all properties from its parent server resource and adds:

| Property Name | Description |
| ------------- | ----------- |
| `Database`    | The name of the RavenDB database |

The full connection string for the database resource uses the format `URL={server URI};Database={DatabaseName}`:

```
URL=http://localhost:8080;Database=ravendb
```

## Connect from your app

Pick the language your consuming app is written in. Each example assumes your AppHost adds a RavenDB server resource named `ravenServer` and a database resource named `ravendb`, and references the database from the consuming app.

For C# apps, the recommended approach is the Aspire RavenDB client integration. It registers an [`IDocumentStore`](https://ravendb.net/docs/article-page/6.2/csharp/client-api/what-is-a-document-store) through dependency injection and adds health checks and telemetry automatically. If you'd rather read environment variables directly, see the [Read environment variables](#read-environment-variables-in-c) section at the end of this tab.

#### Install the client integration

Install the [📦 CommunityToolkit.Aspire.RavenDB.Client](https://nuget.org/packages/CommunityToolkit.Aspire.RavenDB.Client) NuGet package in the client-consuming project:

<InstallDotNetPackage packageName="CommunityToolkit.Aspire.RavenDB.Client" />

The RavenDB client integration registers an `IDocumentStore` instance, which serves as the entry point for interacting with the RavenDB server. If your AppHost includes RavenDB database resources, the associated `IDocumentSession` and `IAsyncDocumentSession` instances are also registered for dependency injection.

#### Add the RavenDB client

In _Program.cs_, call `AddRavenDBClient` on your `IHostApplicationBuilder` to register an `IDocumentStore`:

```csharp title="C# — Program.cs"
builder.AddRavenDBClient(connectionName: "ravendb");
```
**Tip:** The `connectionName` must match the RavenDB database resource name from the AppHost. For more information, see [Add RavenDB server resource and database resource](../ravendb-host/#add-ravendb-server-resource-and-database-resource).

Resolve the document store through dependency injection:

```csharp title="C# — ExampleService.cs"
public class ExampleService(IDocumentStore store)
{
    // Use store...
}
```

#### Add RavenDB client using settings

The `AddRavenDBClient` method provides overloads that accept a `RavenDBClientSettings` object for connecting to an existing RavenDB instance without relying on the hosting integration:

```csharp title="C# — Program.cs"
var settings = new RavenDBClientSettings
{
    Urls = new[] { serverUrl },
    DatabaseName = myDatabaseName,
    Certificate = myCertificate
};

builder.AddRavenDBClient(settings: settings);
```

#### Add keyed RavenDB clients

To register multiple `IDocumentStore` instances with different connection configurations, use `AddKeyedRavenDBClient`:

```csharp title="C# — Program.cs"
builder.AddKeyedRavenDBClient(serviceKey: "production", connectionName: "production");
builder.AddKeyedRavenDBClient(serviceKey: "testing", connectionName: "testing");
```

Then resolve each instance by key:

```csharp title="C# — ExampleService.cs"
public class ExampleService(
    [FromKeyedServices("production")] IDocumentStore production,
    [FromKeyedServices("testing")] IDocumentStore testing)
{
    // Use stores...
}
```

#### Configuration

The Aspire RavenDB client integration offers multiple ways to provide configuration.

**Connection strings.** When using a connection string from the `ConnectionStrings` configuration section, pass the connection name to `AddRavenDBClient`:

```csharp title="C# — Program.cs"
builder.AddRavenDBClient("ravendb");
```

The connection string is resolved from the `ConnectionStrings` section:

```json title="JSON — appsettings.json"
{
  "ConnectionStrings": {
    "ravendb": "URL=http://localhost:8080;Database=ravendb"
  }
}
```

**Configuration providers.** The client integration supports `Microsoft.Extensions.Configuration`. It loads `RavenDBClientSettings` from _appsettings.json_ (or any other configuration source) by using the `Aspire:RavenDB:Client` key:

```json title="JSON — appsettings.json"
{
  "Aspire": {
    "RavenDB": {
      "Client": {
        "ConnectionString": "URL=http://localhost:8080;Database=ravendb",
        "DisableHealthChecks": false,
        "HealthCheckTimeout": 10000,
        "DisableTracing": false
      }
    }
  }
}
```

**Inline delegates.** Pass an `Action<RavenDBClientSettings>` to configure settings inline, for example to disable health checks:

```csharp title="C# — Program.cs"
builder.AddRavenDBClient(
    connectionName: "ravendb",
    configureSettings: settings =>
    {
        settings.CreateDatabase = true;
        settings.Certificate = myCertificate;
        settings.DisableTracing = true;
    });
```

#### Client integration health checks

Aspire client integrations enable health checks by default. The RavenDB client integration adds a health check that verifies the RavenDB server or database is reachable. The health check is wired into the `/health` HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

#### Read environment variables in C\#

If you prefer not to use the Aspire client integration, you can read the Aspire-injected URI from the environment and connect directly using the [`RavenDB.Client`](https://www.nuget.org/packages/RavenDB.Client/) NuGet package:

```csharp title="C# — Program.cs"
using Raven.Client.Documents;

var uri = Environment.GetEnvironmentVariable("RAVENDB_URI");
var database = Environment.GetEnvironmentVariable("RAVENDB_DATABASE");

using var store = new DocumentStore
{
    Urls = [uri!],
    Database = database
}.Initialize();

// Use store to interact with RavenDB...
```

Use the official [`ravendb-go-client`](https://github.com/ravendb/ravendb-go-client) library:

```bash title="Terminal"
go get github.com/ravendb/ravendb-go-client
```

Read the injected environment variables and connect:

```go title="Go — main.go"
package main

import (
    "fmt"
    "os"
    ravendb "github.com/ravendb/ravendb-go-client"
)

func main() {
    // Read Aspire-injected connection properties
    serverURL := os.Getenv("RAVENDB_URI")
    database := os.Getenv("RAVENDB_DATABASE")

    store, err := ravendb.NewDocumentStore([]string{serverURL}, database)
    if err != nil {
        panic(err)
    }
    defer store.Close()

    if err = store.Initialize(); err != nil {
        panic(err)
    }

    fmt.Println("Connected to RavenDB at", serverURL)
}
```

Install the [`ravendb`](https://pypi.org/project/ravendb/) Python client:

```bash title="Terminal"
pip install ravendb
```

Read the injected environment variables and connect:

```python title="Python — app.py"
import os
from ravendb import DocumentStore

# Read Aspire-injected connection properties
server_url = os.getenv("RAVENDB_URI")
database = os.getenv("RAVENDB_DATABASE")

store = DocumentStore(urls=[server_url], database=database)
store.initialize()

# Use store to interact with RavenDB...
```

Install the [`ravendb`](https://www.npmjs.com/package/ravendb) npm package:

```bash title="Terminal"
npm install ravendb
```

Read the injected environment variables and connect:

```typescript title="TypeScript — index.ts"
import { DocumentStore } from 'ravendb';

// Read Aspire-injected connection properties
const serverUrl = process.env.RAVENDB_URI!;
const database = process.env.RAVENDB_DATABASE!;

const store = new DocumentStore([serverUrl], database);
store.initialize();

// Use store to interact with RavenDB...
```
**Tip:** If your app expects specific environment variable names different from the Aspire defaults, you can pass individual connection properties from the AppHost using `WithEnvironment`. See the [AppHost reference](/get-started/app-host/) for details.