Skip to main content

Server: Running an Embedded Instance

Overview

RavenDB can be easily embedded in your application.
Use the Embedded package to integrate RavenDB in just a few easy steps.

EmbeddedServer.Instance.StartServer();
using (var store = EmbeddedServer.Instance.GetDocumentStore("Embedded"))
{
using (var session = store.OpenSession())
{
// Your code here
}
}

Prerequisites and Recommendations

  • Prerequisites

  • Recommendations

    • Projects targeting .NET Framework 4.6.1+ that use the old packages.config for NuGet packages maintenance, should migrate to PackageReference package management.
      Find additional details below.

.NET Core Runtime:

RavenDB Embedded does not include the .NET Core runtime engine required for its operation.

By default, ServerOptions.FrameworkVersion is set to the .NET Core version that we compiled the server with and ServerOptions.DotNetPath is set to dotnet - meaning it is required to have it declared in PATH.

We highly recommend using the .NET Core framework version defined in ServerOptions.FrameworkVersion for proper server function.
You can download the .NET Core runtime engine here.

Migrating from packages.config to PackageReference in old csproj projects:

Due to NuGet limitations, we recommend installing the Embedded package via newer package management, using PackageReference rather than the older packages.config.

The transition between the two is made easy by the built-in Visual Studio migrator.
Find further guidance in this Microsoft article.

Please note that binding redirects in App.config are still required when 'PackageReference' is used in old csproj projects. Failing to use binding redirects might result in an assembly load exception such as:

Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.0, Culture=neutral, 
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.4.1" newVersion="4.0.4.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Installation

  • Create a new project (.NET Standard 2.0+, .NET Core 2.0+, .NET Framework 4.6.1+).
  • Grab our NuGet package
Install-Package RavenDB.Embedded -Version 4.1.0

Starting the Server

RavenDB Embedded Server is available under EmbeddedServer.Instance.
Start the server using the StartServer method.

// Start RavenDB Embedded Server with default options
EmbeddedServer.Instance.StartServer();

For more control over the server startup, pass StartServer a ServerOptions object.

Server Options

Set ServerOptions to change server settings such as .NET FrameworkVersion, DataDirectory, and additional options.

NameTypeDescription
DataDirectorystringIndicates where your data should be stored
DotNetPathstringThe path to exec dotnet (if it is in PATH, leave it)
AcceptEulaboolIf set to false, will ask to accept our terms & conditions
ServerUrlstringWhat address we want to start our server (default 127.0.0.1:0)
MaxServerStartupTimeDurationTimeSpanThe timeout for the server to start
CommandLineArgsList<string>The command lines arguments to start the server with
ServerDirectorystringThe path to the server binary files<sup>*
EmbeddedServer.Instance.StartServer(new ServerOptions
{
DataDirectory = "C:\\RavenData",
ServerUrl = "http://127.0.0.1:8080"
});

If ServerOptions is not provided, RavenDB server will start with a default value of 127.0.0.1:{Random Port}.

Setting Server Directory:

In case you are not interested in installing the .NET run-time environment on your system, you can -

  • Download a full RavenDB version.
    This version already includes a .NET run-time environment.
  • Extract the downloaded version to a local folder.
    E.g. C:\RavenDB
  • Set the ServerDirectory server option to the RavenDB subfolder that contains -
    • Raven.Server.exe in Windows
    • Raven.Server in Posix
EmbeddedServer.Instance.StartServer(new ServerOptions
{
ServerDirectory = @"C:\RavenDB\Server"
});

Restarting the Server:

To restart the server, use the <embedded server>.RestartServerAsync() method.

public async Task RestartServerAsync();

In code:

await EmbeddedServer.Instance.RestartServerAsync();

ServerProcessExited Event:

Use <embedded server>.ServerProcessExited to observe when the server has crashed or exited.

event EventHandler<ServerProcessExitedEventArgs>? ServerProcessExited;

Event data is of type ServerProcessExitedEventArgs.

Embedded server licensing

  • The same license types available for Standalone RavenDB servers, are available for Embedded servers.
  • A licensed server can be managed using Studio, and is given a superior feature set to that of non-registered servers. See the full list of license types and their features here.
  • An embedded server can be licensed using Configuration options or an Environment variable.

Licensing configuration options

Embedded server licensing configuration options are gathered in the ServerOptions.Licensing class.
After acquiring a license, it can be passed to the server either as a string or as a file.

  • To pass your license to the server as a string, use the ServerOptions.LicensingOptions.License configuration option.
EmbeddedServer.Instance.StartServer(new ServerOptions
{
Licensing = new ServerOptions.LicensingOptions
{
License = "your license here"
}
});
  • To keep your license file in your file system and point the server to its path, use the ServerOptions.LicensingOptions.LicensePath configuration option.
EmbeddedServer.Instance.StartServer(new ServerOptions
{
Licensing = new ServerOptions.LicensingOptions
{
LicensePath = "path to license.json file"
}
});

Available LicensingOptions configuration options:

NameTypeDescription
LicensestringSpecifies the full license string directly in the configuration.
If both License and LicensePath are defined, License takes precedence.
LicensePathstringSpecifies a path to a license file.
If both License and LicensePath are defined, License takes precedence.
Default: license.json
EulaAcceptedboolSet to false to present a request to accept our terms & conditions.
DisableAutoUpdateboolDisable automatic license updates (from both the api.ravendb.net license server and the License and LicensePath configuration options).
DisableAutoUpdateFromApiboolDisable automatic license updates from the api.ravendb.net license server.
Note: when disabled, the license can still be updated using the License and LicensePath configuration options.
DisableLicenseSupportCheckboolControl whether to verify the support status of the current license and display it within Studio.
true: disable verification
false: enable verification
ThrowOnInvalidOrMissingLicenseboolThrow an exception if the license is missing or cannot be validated.

License an embedded server using an Environment variable

You can pass the same configuration options to the embedded server using environment variables.

  • To pass your license to the server as a string, define or edit the environment variable RAVEN_License.
    Provide your license as a value for this variable.
    Note, however, that you must first reformat the license JSON that you acquired, and turn it to a single line, eliminating new-line symbols.
{
"Id": "bad5fe9b-fba4-459c-9220-36b438e06e36",
"Name": "rdb",
"Keys": [
"WBRG3G1zKd536ELfRbWw7x69J",
"zyFCZ+AcGLI9RgSyRq5r4KS7K",
"E0hMr5uzmbMBuxAI6WLBXZTSN",
"t+vGjgrVzqoycTPhHdQxNCK2v",
"7xOwXKUblAhZmHcDeY3xvF0jn",
"EZoZLdaeF0D8FFddNB8NrMWeQ",
"kwzAKfs1BMlXi9ZJsVZO9ABUE",
"yBSYoSQMqKywtLi8wJzEyMzQV",
"Fjc4OTo7PD0+nwIfIJ8CICCfA",
"iEgnwIjIEMkRAlieVc="
]
}

You can reformat the license manually, or use a script to do it.
E.g., find below a Bash script that specifies the name of the file from which the license will be read, and then uses the -c flag to compact the file's contents to a single line.

INPUT_FILE="license.json"
jq -c . "$INPUT_FILE"
  • Or, you can keep your license file in a folder accessible to the application that embeds your server, and provide the path to the license file in the RAVEN_LicensePath environment variable.

.NET FrameworkVersion

The default FrameworkVersion is defined to work with any .NET version from the time of the RavenDB server release and newer by using the + moderator.
E.g. ServerOptions.FrameworkVersion = 3.1.17+

Thus, by leaving the default FrameworkVersion definition, RavenDB embedded servers will automatically look for the .NET version that is currently running on the machine, starting from the version at the time of the server release.

Each RavenDB release is compiled with the .NET version that was current at the time of the release.

  • To find which .NET version supports RavenDB 5.1, for example, open the RavenDB 5.1 What's New page.
    The correct .NET version for RavenDB 5.1, .NET 5.0.6., is listed at the bottom of the Server section.
  • By default, your RavenDB server will look for .NET 5.0.6, 5.0.7, etc.
    So as long as you have at least one of these .NET versions running on your machine, RavenDB will work well.

To stay within a major or minor .NET release, but ensure flexibility with patch releases, use a floating integer x.
It will always use the newest version found on your machine.

E.g., ServerOptions.FrameworkVersion = 3.x will look for the newest 3.x release,
ServerOptions.FrameworkVersion = 3.2.x will look for the newest 3.2 release.
Neither will look for 4.x.

ServerOption NameTypeDescription
FrameworkVersionstringThe .NET Core framework version to run the server with
ParameterDescription
nullThe server will pick the newest .NET version installed on your machine.
3.1.17+Default setting (Actual version number is set at the time of server release).
In this example, the server will work properly with .NET patch releases that are greater than or equal to 3.1.17
3.1.17The server will only work properly with this exact .NET release.
3.1.xThe server will pick the newest .NET patch release on your machine.
3.xThe server will pick the newest .NET minor releases and patch releases on your machine.
EmbeddedServer.Instance.StartServer(new ServerOptions
{
FrameworkVersion = "3.1.15+",
});

Security

RavenDB Embedded supports running a secured server. Just run Secured method in the ServerOptions object.

Set up security using the certificate path:

var serverOptions = new ServerOptions();
serverOptions.Secured(
certificate: "PathToServerCertificate",
certPassword: "CertificatePassword");

The first way to enable authentication is to set the certificate with the path to your .pfx server certificate.
You can supply the certificate password using certPassword.

Set up security using a custom script:

To access the certificate via logic that is external to RavenDB, you can use the following approach:

var serverOptionsWithExec = new ServerOptions();
var certificate = new X509Certificate2(fileName, password);
serverOptionsWithExec.Secured(
certLoadExec: "powershell",
certExecArgs: "C:\\secrets\\give_me_cert.ps1",
serverCertThumbprint: certificate.Thumbprint,
clientCert: certificate);

This option is useful when you want to protect your certificate (private key) with other solutions such as "Azure Key Vault", "HashiCorp Vault" or even Hardware-Based Protection. RavenDB will invoke a process you specify, so you can write your own scripts / mini-programs and apply the logic that you need.

This way a clean separation is kept between RavenDB and the secret store in use.

RavenDB expects to get the raw binary representation (byte array) of the .pfx certificate through the standard output.

Document Store

After starting the server you can get the DocumentStore from the Embedded Server and start working with RavenDB.
Getting the DocumentStore from The Embedded Server is done simply by calling GetDocumentStore or GetDocumentStoreAsync with the name of the database you choose to work with.

EmbeddedServer.Instance.GetDocumentStore("Embedded");

For additional control over the process you can call the methods with a DatabaseOptions object.

NameTypeDescription
DatabaseRecordDatabaseRecordInstance of DatabaseRecord containing database configuration
SkipCreatingDatabaseboolIf set to true, will skip try creating the database
var databaseOptions = new DatabaseOptions(new DatabaseRecord
{
DatabaseName = "Embedded"
});
EmbeddedServer.Instance.GetDocumentStore(databaseOptions);

Get Server URL and Process ID

Server URL:

The GetServerUriAsync method can be used to retrieve the Embedded server URL.
It must be called after the server was started, because it waits for the server's initialization to complete.
The URL can be used, for example, to create a custom document store, omitting the GetDocumentStore method entirely.

Uri url = await EmbeddedServer.Instance.GetServerUriAsync();

Process ID:

The GetServerProcessIdAsync method can be used to retrieve the system-generated process ID for the embedded server.

public async Task<int> GetServerProcessIdAsync(CancellationToken token = default);
int processID = await EmbeddedServer.Instance.GetServerProcessIdAsync();

Remarks

  • You can have only one instance of EmbeddedServer.
  • The EmbeddedServer.Instance.OpenStudioInBrowser() method can be used to open a browser instance with Studio.