Docs / Dependency Injection

Dependency Injection

What this page covers#

This page explains how to register MooDb with dependency injection and when to choose the simple direct registration path or the factory path.

The simple version#

If your application talks to one database, register a concrete MooDbContext directly.

If your application needs to choose between different databases at runtime, register the MooDbContextFactory instead. .

Start with the simple path unless you have a real reason to move to the factory path.

The straight registration path#

If your application uses one database, the simplest approach is to register a concrete MooDbContext directly.

</> C#
builder.Services.AddScoped<MooDbContext>(_ =>
    new MooDbContext(builder.Configuration.GetConnectionString("DefaultConnection")!));

Lifetime guidance#

For most applications, MooDbContext should be registered as either scoped or transient.

A singleton lifetime is not a good fit for this model.

The factory path#

If your application needs to connect to different databases at runtime, use AddMooDbContextFactory() instead.

This is useful for multi-database systems, for example a SaaS product with a database-per-tenant architecture, or any application where the correct database must be selected at runtime.

</> C#
using MooDb.DependencyInjection;

builder.Services.AddMooDbContextFactory();

You can also configure default factory-created MooDb options:

</> C#
using MooDb.DependencyInjection;

builder.Services.AddMooDbContextFactory(options =>
{
    options.CommandTimeoutSeconds = 60;
    options.StrictAutoMapping = true;
});

Important notes#

  • direct registration is the simplest path
  • the factory path is for runtime database selection
  • the application still decides which connection string to use
  • the factory only creates MooDbContext instances from that caller-supplied target