Skip to content

Contexts and Configuration

Mike Christensen edited this page Aug 28, 2026 · 2 revisions

Contexts and configuration

Choose a context based on storage and scale, then initialize it once.

StaticContext

var context = StaticContext.Configure
   .DataDirectory(Path.Combine(AppContext.BaseDirectory, "SampleData"))
   .Identity(() => AuthIdentity.Anonymous)
   .Create();
context.Initialize();

The directory must contain KPCData.xml, or KPCData.gz when .CompressedStore is selected. Use StaticContext for examples, tests, import sources, and small tools. It does not write mutations back to the snapshot and is not intended for concurrent production workloads or large recipe catalogs.

DBContext

dotnet add package KitchenPC.Core --version 2.0.0
dotnet add package KitchenPC.DB --version 2.0.0
using FluentNHibernate.Cfg.Db;
using KitchenPC.Core;
using KitchenPC.Core.Context;
using KitchenPC.DB;

var context = DBContext.Configure
   .Adapter(DatabaseAdapter.Configure
      .DatabaseConfiguration(
         PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString))
      .SearchProvider(NHSearch.Instance))
   .Capabilities(DBContextCapabilities.IngredientParsing)
   .Identity(() => AuthIdentity.Anonymous)
   .Create();
context.Initialize();

NHSearch is the built-in SQL search provider. Supply another ISearchProvider factory for database-native full-text search or an external index. Keep credentials in configuration, environment variables, user secrets, or a deployment secret store.

Configuration wrapper

Integration code can package construction as IConfiguration<T>:

var configuration = Configuration<DBContext>.Build
   .Context(DBContext.Configure
      .Adapter(/* adapter builder */)
      .Capabilities(DBContextCapabilities.IngredientParsing)
      .Identity(() => AuthIdentity.Anonymous))
   .Create();

var context = configuration.InitializeContext();

ASP.NET Core's AddKPCContext consumes this wrapper.

Logging

Both context builders accept the standard Microsoft.Extensions.Logging.ILoggerFactory. Logging is optional and is disabled by default:

var context = DBContext.Configure
   .Logging(loggerFactory)
   .Adapter(/* adapter builder */)
   .Identity(() => AuthIdentity.Anonymous)
   .Create();

The logger factory is also used by database import/export, NLP tracing, and the recipe modeler. See Logging and diagnostics for configuration examples and categories.

Lifetime rules

  • Initialize once at process startup.
  • Reuse the context and create user views with AsUserContext.
  • Do not reinitialize a user view.
  • Dispose an owned DatabaseAdapter during shutdown.
  • Prefer async database methods in request-handling code.
  • Enable only needed DBContext capabilities.

Clone this wiki locally