Session: Opening a Session

To open synchronous session use the OpenSession method from DocumentStore or OpenAsyncSession if you prefer working in an asynchronous manner.

Syntax

There are three overloads of OpenSession / OpenAsyncSession methods

// Open session for a 'default' database configured in 'DocumentStore'
IDocumentSession OpenSession();

// Open session for a specified database
IDocumentSession OpenSession(string database);

IDocumentSession OpenSession(SessionOptions options);
// Open session for a 'default' database configured in 'DocumentStore'
IAsyncDocumentSession OpenAsyncSession();

// Open session for a specified database
IAsyncDocumentSession OpenAsyncSession(string database);

IAsyncDocumentSession OpenAsyncSession(SessionOptions options);

The first method is an equivalent of doing

store.OpenSession(new SessionOptions());
store.OpenAsyncSession(new SessionOptions());

The second method is an equivalent of doing

store.OpenSession(new SessionOptions
{
    Database = databaseName
});
store.OpenAsyncSession(new SessionOptions
{
    Database = databaseName
});
Parameters
options OpenSessionOptions Options containing information such as name of database and RequestExecutor.
Return Value
IDocumentSession / IAsyncDocumentSession Instance of a session object.

Example

using (IDocumentSession session = store.OpenSession())
{
    // code here
}
using (IAsyncDocumentSession session = store.OpenAsyncSession())
{
    // async code here
}

Important

Always remember to release session allocated resources after usage by invoking the Dispose method or wrapping the session object in the using statement.