Skip to content
On this page

Do It Yourself IoC Integration


The Marten team recommends using the IServiceCollection.AddMarten() extension method for IoC integration out of the box.

The Marten team has striven to make the library perfectly usable without the usage of an IoC container, but you may still want to use an IoC container specifically to manage dependencies and the life cycle of Marten objects. While the IServiceCollection.AddMarten() method is the recommended way to integrate Marten into an IoC container, you can certainly recreate that functionality in the IoC container of your choice.


Lamar supports the .Net Core abstractions for IoC service registrations, so you could happily use the AddMarten() method directly with Lamar as well.

Using Lamar as the example container, we recommend registering Marten something like this:

public class MartenServices : ServiceRegistry
    public MartenServices()
        ForSingletonOf<IDocumentStore>().Use(c =>
            return DocumentStore.For(options =>
                options.Connection("your connection string");
                options.AutoCreateSchemaObjects = AutoCreate.None;

                // other Marten configuration options

        // Register IDocumentSession as Scoped
            .Use(c => c.GetInstance<IDocumentStore>().LightweightSession())

        // Register IQuerySession as Scoped
            .Use(c => c.GetInstance<IDocumentStore>().QuerySession())

snippet source | anchor

There are really only two key points here:

  1. There should only be one IDocumentStore object instance created in your application, so I scoped it as a "Singleton" in the StructureMap container
  2. The IDocumentSession service that you use to read and write documents should be scoped as "one per transaction." In typical usage, this ends up meaning that an IDocumentSession should be scoped to a single HTTP request in web applications or a single message being handled in service bus applications.

Released under the MIT License.