Skip to content

Use this LLM Friendly Docs as an MCP server for Marten.

The search box in the website knows all the secrets—try it!

For any queries, join our Discord Channel to reach us faster.

JasperFx Logo

JasperFx provides formal support for Marten and other JasperFx libraries. Please check our Support Plans for more details.

Bootstrapping Marten ​

As briefly shown in the getting started page, Marten comes with the AddMarten() extension method for the .NET IServiceCollection to quickly add Marten to any ASP.NET Core or Worker Service application:

cs
// This is the absolute, simplest way to integrate Marten into your
// .NET application with Marten's default configuration
builder.Services.AddMarten(options =>
{
    // Establish the connection string to your Marten database
    options.Connection(builder.Configuration.GetConnectionString("Marten")!);

    // If you want the Marten controlled PostgreSQL objects
    // in a different schema other than "public"
    options.DatabaseSchemaName = "other";

    // There are of course, plenty of other options...
})

// This is recommended in new development projects
.UseLightweightSessions()

// If you're using Aspire, use this option *instead* of specifying a connection
// string to Marten
.UseNpgsqlDataSource();

snippet source | anchor

The AddMarten() method will add these service registrations to your application:

  1. IDocumentStore with a Singleton lifetime. The document store can be used to create sessions, query the configuration of Marten, generate schema migrations, and do bulk inserts.
  2. IDocumentSession with a Scoped lifetime for all read and write operations. By default (as of Marten 9.0.3), sessions are lightweight with no identity map tracking (DocumentTracking.None)
  3. IQuerySession with a Scoped lifetime for all read operations against the document store.

For more information, see:

At runtime, when your application needs to resolve IDocumentStore for the first time, Marten will:

  1. Resolve a StoreOptions object from the initial AddMarten() configuration
  2. Apply all registered IConfigureMarten services to alter that StoreOptions object
  3. Read the application's JasperFxOptions, and take from it whatever you did not set on StoreOptions yourself: TenantIdStyle and ApplicationAssembly, and from the active profile, AutoCreateSchemaObjects (the profile's ResourceAutoCreate) and ResourceMigrationFailureMode. JasperFx works out the active profile and the application assembly from the IHostEnvironment
  4. Attach any IInitialData services that were registered in the IoC container to the StoreOptions object
  5. Finally, Marten builds a new DocumentStore object using the now configured StoreOptions object

IAsyncConfigureMarten services are applied to the same StoreOptions object, but from a hosted service when the host starts, which AddMarten() registers ahead of the other hosted services. If anything resolves IDocumentStore before the host starts, the store is built without them. See Using IoC Services for Configuring Marten.

This model is comparable to the .Net IOptions model.

Register DocumentStore with AddMarten() ​

INFO

All the examples in this page are assuming the usage of the default IoC container Microsoft.Extensions.DependencyInjection, but Marten can be used with any IoC container or with no IoC container whatsoever.

First, if you are using Marten completely out of the box with no customizations (besides attributes on your documents), you can just supply a connection string to the underlying Postgresql database like this:

cs
var connectionString = Configuration.GetConnectionString("postgres");

// By only the connection string
services.AddMarten(connectionString);

snippet source | anchor

The second option is to supply a nested closure to configure Marten inline like so:

TIP

The samples below use CritterStackDefaults(...) to wire per-environment defaults for resource auto-create and code generation mode. CritterStackDefaults and the underlying JasperFxOptions are part of the shared JasperFx infrastructure that Marten and Wolverine consume in common — see the JasperFx shared libraries documentation for the full set of options and how development / production defaults are resolved.

ResourceAutoCreate is the default AutoCreate for every stateful resource in the application, so setting it to None for Production turns off automatic schema migration for Marten and for Wolverine's message storage in one place. The schema still has to get there somehow; see Schema Migrations and Patches for the deployment-time options.

cs
var connectionString = Configuration.GetConnectionString("postgres");

services.AddMarten(opts =>
{
    opts.Connection(connectionString);
});

// In a "Production" environment, we're turning off the
// automatic database migrations and dynamic code generation
services.CritterStackDefaults(x =>
{
    x.Production.ResourceAutoCreate = AutoCreate.None;
});

snippet source | anchor

Lastly, if you prefer, you can pass a Marten StoreOptions object to AddMarten() like this example:

cs
var connectionString = Configuration.GetConnectionString("postgres");

// Build a StoreOptions object yourself
var options = new StoreOptions();
options.Connection(connectionString);

services.AddMarten(options);

// In a "Production" environment, we're turning off the
// automatic database migrations and dynamic code generation
services.CritterStackDefaults(x =>
{
    x.Production.ResourceAutoCreate = AutoCreate.None;
});

snippet source | anchor

NpgsqlDataSource ​

TIP

Npgsql's own logging is off by default since Marten 9. Set opts.DisableNpgsqlLogging = false to have Marten forward it to the application's ILoggerFactory from any data source Marten builds. A data source you register yourself and pass to Marten with UseNpgsqlDataSource() keeps whatever logging it was built with. See the Npgsql documentation on logging for more information.

TIP

The NpgsqlDataSource registration is also the way to connect with rotating credentials such as Microsoft Entra ID access tokens — see Azure Database for PostgreSQL with Entra ID.

You can also use the NpgsqlDataSource to configure Marten connection settings. From Npgsql docs:

The data source represents your PostgreSQL database and can hand out connections to it or support direct execution of SQL against it. The data source encapsulates the various Npgsql configuration needed to connect to PostgreSQL, as well the connection pooling which makes Npgsql efficient.

You can register the data source with Npgsql's AddNpgsqlDataSource() method, then tell Marten to use it by calling UseNpgsqlDataSource(). Since Npgsql 11, AddNpgsqlDataSource() is part of the Npgsql package itself; the separate Npgsql.DependencyInjection package is gone:

cs
services.AddNpgsqlDataSource(ConnectionSource.ConnectionString);

services.AddMarten()
    .UseLightweightSessions()
    .UseNpgsqlDataSource();

snippet source | anchor

You can also use a dedicated keyed registration. This can be useful for scenarios where you need more than one data source registered:

cs
const string dataSourceKey = "marten_data_source";

services.AddNpgsqlDataSource(ConnectionSource.ConnectionString, serviceKey: dataSourceKey);

services.AddMarten()
    .UseLightweightSessions()
    .UseNpgsqlDataSource(dataSourceKey);

snippet source | anchor

The registered data source only serves its own connection string. Marten builds data sources for any other connection string it needs, such as a tenant database, and another overload of UseNpgsqlDataSource() takes the function that creates their NpgsqlDataSourceBuilder, along with an optional service key:

cs
services.AddNpgsqlDataSource("some connection string");

services.AddMarten()
    .UseLightweightSessions()

    // Marten uses the registered NpgsqlDataSource for its own
    // connection string, and builds data sources for any other
    // connection string (a tenant database, say) from this factory
    .UseNpgsqlDataSource(connectionString =>
    {
        var builder = new NpgsqlDataSourceBuilder(connectionString);
        builder.ConnectionStringBuilder.ApplicationName = "billing-service";
        return builder;
    });

snippet source | anchor

Your function creates the builder in place of new NpgsqlDataSourceBuilder(connectionString). Marten still applies its own configuration on top of it, whether it was added before or after: everything added with ConfigureNpgsqlDataSourceBuilder(), such as the pgvector or PostGIS type mappings, and Npgsql logging when DisableNpgsqlLogging = false.

Multi-Host Data Source (Read Replicas) ​

Marten includes support for NpgsqlMultiHostDataSource, allowing you to spread queries over your read replicas, potentially improving throughput in read-heavy applications. To get started, your connection string should specify your primary host along a list of replicas, per Npgsql documentation:

ps
Host=my-db-host.com,my-db-host-readonly-1.com;Database=marten;...

Configuring NpgsqlMultiHostDataSource is very similar to a normal data source, simply swapping it for AddMultiHostNpgsqlDataSource. Marten will always use the primary node for queries with a NpgsqlMultiHostDataSource unless you explicitly opt to use the standby nodes. You can adjust what type of node Marten uses for querying via the MultiHostSettings store options:

cs
services.AddMultiHostNpgsqlDataSource(ConnectionSource.ConnectionString);

services.AddMarten(x =>
    {
        // Will prefer standby nodes for querying.
        x.Advanced.MultiHostSettings.ReadSessionPreference = TargetSessionAttributes.PreferStandby;
    })
    .UseLightweightSessions()
    .UseNpgsqlDataSource();

snippet source | anchor

WARNING

Marten will only use your read node preference with queries run with IQuerySession that are using a Marten-managed connection lifetime.

Every other connection, including queries executed via IDocumentSession and internal queries (ie async daemon), uses MultiHostSettings.WriteSessionPreference. That defaults to TargetSessionAttributes.ReadWrite, a node that accepts writes, to ensure write-side consistency.

WriteSessionPreference can be set too, for example to insist on the primary node:

cs
services.AddMultiHostNpgsqlDataSource("some connection string");

services.AddMarten(x =>
    {
        // Queries from IQuerySession may go to a standby
        x.Advanced.MultiHostSettings.ReadSessionPreference = TargetSessionAttributes.PreferStandby;

        // Everything else must reach the primary
        x.Advanced.MultiHostSettings.WriteSessionPreference = TargetSessionAttributes.Primary;
    })
    .UseNpgsqlDataSource();

snippet source | anchor

For more background, see the blog post Scaling Marten with PostgreSQL Read Replicas.

Composite Configuration with ConfigureMarten() ​

The AddMarten() mechanism assumes that you are expressing all of the Marten configuration in one place and "know" what that configuration is upfront. Consider these possibilities where that isn't necessarily possible or desirable:

  1. You want to override Marten configuration in integration testing scenarios (I do this quite commonly)
  2. Many users have expressed the desire to keep parts of Marten configuration in potentially separate assemblies or subsystems in such a way that they could later break up the current service into smaller services

Fear not, Marten V5.0 introduced a new way to add or modify the Marten configuration from AddMarten(). Let's assume that we're building a system that has a subsystem related to users and want to segregate all the service registrations and Marten configuration related to users into a single place like this extension method:

cs
public static IServiceCollection AddUserModule(this IServiceCollection services)
{
    // This applies additional configuration to the main Marten DocumentStore
    // that is configured elsewhere
    services.ConfigureMarten(opts =>
    {
        opts.RegisterDocumentType<User>();
    });

    // Other service registrations specific to the User submodule
    // within the bigger system

    return services;
}

snippet source | anchor

And next, let's put that into context with its usage inside your application's bootstrapping:

cs
using var host = await Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        // The initial Marten configuration
        services.AddMarten("some connection string");

        // Other core service registrations
        services.AddLogging();

        // Add the User module
        services.AddUserModule();
    }).StartAsync();

snippet source | anchor

The ConfigureMarten() method is the interesting part of the code samples above. That is registering a small service that implements the IConfigureMarten interface into the underlying IoC container:

cs
/// <summary>
///     Mechanism to register additional Marten configuration that is applied after AddMarten()
///     configuration, but before DocumentStore is initialized
/// </summary>
public interface IConfigureMarten: JasperFx.IConfigureStore<StoreOptions>
{
}

snippet source | anchor

You could alternatively implement a custom IConfigureMarten (or IConfigureMarten<T> where T : IDocumentStore if you're working with multiple databases class like so:

cs
internal class UserMartenConfiguration: IConfigureMarten
{
    public void Configure(IServiceProvider services, StoreOptions options)
    {
        options.RegisterDocumentType<User>();
        // and any other additional Marten configuration
    }
}

snippet source | anchor

and registering it in your IoC container something like this:

cs
public static IServiceCollection AddUserModule2(this IServiceCollection services)
{
    // This applies additional configuration to the main Marten DocumentStore
    // that is configured elsewhere
    services.AddSingleton<IConfigureMarten, UserMartenConfiguration>();

    // If you're using multiple databases per Host, register `IConfigureMarten<T>`, like this:
    services.AddSingleton<IConfigureMarten<IInvoicingStore>, InvoicingStoreConfiguration>();

    // Other service registrations specific to the User submodule
    // within the bigger system

    return services;
}

snippet source | anchor

Using IoC Services for Configuring Marten 7.7 ​

There is also a newer mechanism called IAsyncConfigureMarten that was originally built to enable services like the Feature Management library from Microsoft to be used to selectively configure Marten using potentially asynchronous methods and IoC resolved services.

That interface signature is:

cs
/// <summary>
///     Mechanism to register additional Marten configuration that is applied after AddMarten()
///     configuration, but before DocumentStore is initialized when you need to utilize some
///     kind of asynchronous services like Microsoft's FeatureManagement feature to configure Marten
/// </summary>
public interface IAsyncConfigureMarten: JasperFx.IAsyncConfigureStore<StoreOptions>
{
}

snippet source | anchor

As an example from the tests, here's a custom version that uses the Feature Management service:

cs
public class FeatureManagementUsingExtension: IAsyncConfigureMarten
{
    private readonly IFeatureManager _manager;

    public FeatureManagementUsingExtension(IFeatureManager manager)
    {
        _manager = manager;
    }

    public async ValueTask Configure(StoreOptions options, CancellationToken cancellationToken)
    {
        if (await _manager.IsEnabledAsync("Module1"))
        {
            options.Events.MapEventType<Module1Event>("module1:event");
        }
    }
}

snippet source | anchor

And lastly, these extensions can be registered directly against IServiceCollection like so:

cs
services.ConfigureMartenWithServices<FeatureManagementUsingExtension>();

snippet source | anchor

Using Lightweight Sessions ​

TIP

Most usages of Marten should default to the lightweight sessions for better performance

As of Marten 9.0.3, the default registration for IDocumentSession added by AddMarten() is already a lightweight session with no identity map tracking (DocumentTracking.None). If you are explicitly calling .UseLightweightSessions(), that is the recommended approach to make the intent clear in your application bootstrapping, as shown below:

cs
var connectionString = Configuration.GetConnectionString("postgres");

services.AddMarten(opts =>
    {
        opts.Connection(connectionString);
    })

    // Chained helper to replace the built in
    // session factory behavior
    .UseLightweightSessions();

snippet source | anchor

Customizing Session Creation Globally ​

By default (as of Marten 9.0.3), Marten creates a lightweight document session with no identity map tracking and a ReadCommitted transaction isolation level. If you want to use a different configuration for sessions globally in your application, you can use a custom implementation of the ISessionFactory class as shown in this example:

cs
public class CustomSessionFactory: ISessionFactory
{
    private readonly IDocumentStore _store;

    // This is important! You will need to use the
    // IDocumentStore to open sessions
    public CustomSessionFactory(IDocumentStore store)
    {
        _store = store;
    }

    public IQuerySession QuerySession()
    {
        return _store.QuerySession();
    }

    public IDocumentSession OpenSession()
    {
        // Opting for the "lightweight" session
        // option with no identity map tracking
        // and choosing to use RepeatableRead transactions
        // just to be different. A Serializable session has to be
        // opened asynchronously, so it can't come from here
        return _store.LightweightSession(IsolationLevel.RepeatableRead);
    }
}

snippet source | anchor

To register the custom session factory, use the BuildSessionsWith() method as shown in this example:

cs
var connectionString = Configuration.GetConnectionString("postgres");

services.AddMarten(opts =>
    {
        opts.Connection(connectionString);
    })

    // Chained helper to replace the built in
    // session factory behavior
    .BuildSessionsWith<CustomSessionFactory>();

// In a "Production" environment, we're turning off the
// automatic database migrations and dynamic code generation
services.CritterStackDefaults(x =>
{
    x.Production.ResourceAutoCreate = AutoCreate.None;
});

snippet source | anchor

The session factories can also be used to build out and attach custom IDocumentSessionListener objects or replace the logging as we'll see in the next section.

See diagnostics and instrumentation for more information.

Customizing Session Creation by Scope ​

From a recent user request to Marten, what if you want to log the database statement activity in Marten with some kind of correlation to the active HTTP request or service bus message or some other logical session identification in your application? That's now possible by using a custom ISessionFactory.

Taking the example of an ASP.NET Core application, let's say that you have a small service scoped to an HTTP request that tracks a correlation identifier for the request like this:

cs
public interface ISession
{
    Guid CorrelationId { get; set; }
}

snippet source | anchor

And a custom Marten session logger to add the correlation identifier to the log output like this:

cs
public class CorrelatedMartenLogger: IMartenSessionLogger
{
    private readonly ILogger<IDocumentSession> _logger;
    private readonly ISession _session;

    public CorrelatedMartenLogger(ILogger<IDocumentSession> logger, ISession session)
    {
        _logger = logger;
        _session = session;
    }

    public void LogSuccess(NpgsqlCommand command)
    {
        // Do some kind of logging using the correlation id of the ISession
    }

    public void LogFailure(NpgsqlCommand command, Exception ex)
    {
        // Do some kind of logging using the correlation id of the ISession
    }

    public void LogSuccess(NpgsqlBatch batch)
    {
        // Do some kind of logging using the correlation id of the ISession
    }

    public void LogFailure(NpgsqlBatch batch, Exception ex)
    {
        // Do some kind of logging using the correlation id of the ISession
    }

    public void RecordSavedChanges(IDocumentSession session, IChangeSet commit)
    {
        // Do some kind of logging using the correlation id of the ISession
    }

    public void OnBeforeExecute(NpgsqlCommand command)
    {

    }

    public void LogFailure(Exception ex, string message)
    {

    }

    public void OnBeforeExecute(NpgsqlBatch batch)
    {

    }
}

snippet source | anchor

Now, let's move on to building out a custom session factory that will attach our correlated marten logger to sessions being resolved from the IoC container:

cs
public class ScopedSessionFactory: ISessionFactory
{
    private readonly IDocumentStore _store;
    private readonly ILogger<IDocumentSession> _logger;
    private readonly ISession _session;

    // This is important! You will need to use the
    // IDocumentStore to open sessions
    public ScopedSessionFactory(IDocumentStore store, ILogger<IDocumentSession> logger, ISession session)
    {
        _store = store;
        _logger = logger;
        _session = session;
    }

    public IQuerySession QuerySession()
    {
        return _store.QuerySession();
    }

    public IDocumentSession OpenSession()
    {
        var session = _store.LightweightSession();

        // Replace the Marten session logger with our new
        // correlated marten logger
        session.Logger = new CorrelatedMartenLogger(_logger, _session);

        return session;
    }
}

snippet source | anchor

Lastly, let's register our new session factory, but this time we need to take care to register the session factory as Scoped in the underlying container so we're using the correct ISession at runtime:

cs
var connectionString = Configuration.GetConnectionString("postgres");

services.AddMarten(opts =>
    {
        opts.Connection(connectionString);
    })
    // Using the "Optimized artifact workflow" for Marten >= V5
    // sets up your Marten configuration based on your environment
    // See https://martendb.io/configuration/optimized_artifact_workflow.html
    // Chained helper to replace the CustomSessionFactory
    .BuildSessionsWith<ScopedSessionFactory>(ServiceLifetime.Scoped);

services.CritterStackDefaults(x =>
{
    x.Production.ResourceAutoCreate = AutoCreate.None;
});

snippet source | anchor

TIP

This correlation tracking might be better with structural logging with something like Serilog, but we'll leave that to users.

Eager Initialization of the DocumentStore ​

Sorry, but as of Marten 7, it is no longer possible to force the DocumentStore to be initialized during IHost bootstrapping. We had to make this change to avoid using any synchronous IO during bootstrapping.

Ancillary Marten Stores 5.0 ​

For the increasingly common usage of Marten within modular monoliths or for scalability reasons, you can effectively use additional Marten stores in the same application. These stores could either address completely different databases, or use different schemas within the same database.

TIP

The database management tools that come bundled with Marten are able to work with the separately registered document stores along with the default store from AddMarten().

To utilize the type system and your application's underlying IoC container, the first step is to create a custom marker interface for your separate document store like this one below targeting a separate "invoicing" database:

cs
// These marker interfaces *must* be public
public interface IInvoicingStore : IDocumentStore
{

}

snippet source | anchor

A couple notes on the interface:

  1. The custom interface has to be public and implement the IDocumentStore interface
  2. Marten is quietly building a dynamic type for your additional store interface internally

And now to bootstrap that separate store in our system:

cs
using var host = await Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        // You can still use AddMarten() for the main document store
        // of this application
        services.AddMarten("some connection string");

        services.AddMartenStore<IInvoicingStore>(opts =>
            {
                // All the normal options are available here
                opts.Connection("different connection string");

                // more configuration
            })
            // Optionally apply all database schema
            // changes on startup
            .ApplyAllDatabaseChangesOnStartup()

            // Run the async daemon for this database
            .AddAsyncDaemon(DaemonMode.HotCold)

            // Use IInitialData
            .InitializeWith(new DefaultDataSet());

        // In a "Production" environment, we're turning off the
        // automatic database migrations
        services.CritterStackDefaults(x =>
        {
            x.Production.ResourceAutoCreate = AutoCreate.None;
        });
    }).StartAsync();

snippet source | anchor

At runtime we can inject an instance of our new IInvoicingStore and work with it like any other Marten IDocumentStore as shown below in an internal InvoicingService:

cs
public class InvoicingService
{
    private readonly IInvoicingStore _store;

    // IInvoicingStore can be injected like any other
    // service in your IoC container
    public InvoicingService(IInvoicingStore store)
    {
        _store = store;
    }

    public async Task DoSomethingWithInvoices()
    {
        // Important to dispose the session when you're done
        // with it
        await using var session = _store.LightweightSession();

        // do stuff with the session you just opened
    }
}

snippet source | anchor

Session Configuration for Ancillary Stores 8.x ​

Just like the main store configured with AddMarten(), ancillary stores support fluent session configuration to control the default ISessionFactory used for dependency-injected sessions. The session factory is registered as a keyed service keyed by the store marker interface type (e.g., typeof(IInvoicingStore)).

cs
using var host = await Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        services.AddMarten("some connection string");

        services.AddMartenStore<IInvoicingStore>(opts =>
            {
                opts.Connection("different connection string");
            })
            // Use lightweight sessions for this ancillary store
            .UseLightweightSessions();

        // Or use identity map sessions
        // .UseIdentitySessions();

        // Or use dirty-tracked sessions
        // .UseDirtyTrackedSessions();

        // Or use a custom session factory
        // .BuildSessionsWith<CustomSessionFactory>();
    }).StartAsync();

snippet source | anchor

You can resolve the keyed ISessionFactory for an ancillary store directly from the DI container if needed:

csharp
var factory = serviceProvider.GetRequiredKeyedService<ISessionFactory>(typeof(IInvoicingStore));
await using var session = factory.OpenSession();

Finding Every Document Store ​

AllDocumentStores(), an extension method on IServiceProvider, returns the main store from AddMarten(), if there is one, followed by every ancillary store from AddMartenStore<T>(). It is useful for diagnostics or tooling that should cover every store in the application:

cs
// The main store from AddMarten(), if there is one, followed by
// every ancillary store from AddMartenStore<T>()
IReadOnlyList<IDocumentStore> stores = services.AllDocumentStores();

snippet source | anchor

Contributing to the Event Model ​

AddMarten() and AddMartenStore<T>() each register their store as a source for the JasperFx Event Model. When the Event Model is assembled, every projection registered in the store contributes a View slice: the projection, the document it produces, and the events it applies. Slices are named after the document type.

Slices merge into a model by the model's name. Marten picks the name for a store's slices in this order:

  1. StoreOptions.EventModelName, if you set it
  2. Otherwise the JasperFx ServiceName (the entry assembly's name unless you set it), which is also the name Wolverine gives the model it derives
  3. Otherwise EventModel

So if your application declares its own model under another name, set EventModelName to the same name, or you end up with two models. The name is read when the model is assembled, not when the store is registered, so it does not matter whether AddEventModel() is called before or after AddMarten(). An empty or whitespace name throws an ArgumentException; leave it null for the default.

cs
services.AddMarten(opts =>
{
    opts.Connection("some connection string");

    // Contribute this store's projections to the "Billing" model
    opts.EventModelName = "Billing";
});

// The application's own declarations for the same model. The two
// merge by name, and the order of these calls does not matter
services.AddEventModel("Billing", model =>
{
    // declared slices
});

snippet source | anchor

In a modular monolith, give an ancillary store its own EventModelName when it is a bounded context of its own.

Released under the MIT License.