Loaders and build-time services
Load data that does not come from a file with IBevelDataLoader, register build-time services, and track input files.
On this page
[DependsOn("Posts")]
public sealed class PostCountLoader : IBevelDataLoader<int>
{
public string Name => "PostCount";
public Task<int> LoadAsync(BevelLoadContext context, CancellationToken cancellationToken = default)
=> Task.FromResult(context.Get<IReadOnlyList<BlogPost>>("Posts").Count);
}
Write a loader when a dataset does not come from a file. If it does come from a file, but in a format Bevel does not read (TOML, CSV), write a format reader instead (Teach Bevel a new format). You combine datasets, compute values, or call a database. A loader implements IBevelDataLoader<T>. Use [DependsOn] to run it after other datasets. The output is data.PostCount in any page.
Build-time services
Loaders can take constructor dependencies. Write a Data/DataStartup.cs that implements IBevelDataStartup, register your services there, and call the same method from Program.cs:
public static IServiceCollection AddBlogServices(this IServiceCollection services, IConfiguration config)
{
services.Configure<BlogOptions>(config.GetSection("Blog"));
services.AddSingleton<IReadingTimeCalculator, ReadingTimeCalculator>();
return services;
}
public sealed class DataStartup : IBevelDataStartup
{
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
=> services.AddBlogServices(configuration);
}
// Program.cs
builder.Services.AddBlogServices(builder.Configuration);
- Processors and groupers use the same services.
- Built in:
IConfiguration,IHostEnvironment,BevelLoadContextandILogger<T>. - Each loader runs in its own scope.
- Configuration follows
WebApplication.CreateBuilder. See Build environment. - Prebuild compiles
Data/**/*.cson its own, using your project's global usings (including the SDK's implicit usings),LangVersion,NullableandDefineConstants. Types from your other project folders are not visible there. A global using whose namespace prebuild cannot find is skipped and logged. - Packages used by
Data/**/*.cs(EF Core, Microsoft.Data.Sqlite) load in an isolated context. A package that needs a newerMicrosoft.Extensions.*assembly than the SDK ships will not work at build time.
Tell Bevel which files a loader reads
The data step skips itself when no input changed.
- Files read through
context.Read*Asynchelpers (ReadJsonAsync,ReadYamlAsync,ReadMarkdownAsync,ReadXmlAsyncand their directory variants) are tracked automatically. - A file you read yourself needs
context.RegisterInputFile(path). UseRegisterInputDirectoryfor a folder whose listing you read, andRegisterRecursiveInputDirectorywhen you read it recursively, so added and removed files count too. - Databases and APIs cannot be tracked. Set
BevelPrebuildAlwaysRuntotrueso the step runs every build. See MSBuild.BevelPrebuildAlwaysRun. - Do not decide anything from the clock, such as
DateTime.Now. The data is built once and frozen, and an incremental build reuses it, so a "supported until" check goes stale. Store the answer in the data instead.
public sealed class CountriesLoader : IBevelDataLoader<IReadOnlyList<string>>
{
public string Name => "Countries";
public Task<IReadOnlyList<string>> LoadAsync(BevelLoadContext context, CancellationToken cancellationToken = default)
{
var path = context.ResolvePath("Data/Countries/countries.txt");
context.RegisterInputFile(path); // we read the file ourselves, so register it
return Task.FromResult<IReadOnlyList<string>>(File.ReadAllLines(path));
}
}
How incremental builds decide
The BevelPrebuild target has inputs and outputs, so MSBuild skips it when nothing changed. Inputs are Data/**/* (all formats), appsettings*.json, bevel.json, the project file, the prebuild tool, the generated .rsp files, and every file the prebuild recorded in obj/.../Bevel/bevel-inputs.txt. The generated BevelData.g.cs stays in Compile when the target is skipped.
dotnet build --no-incrementaland rebuilds also run it.dotnet watchwatchesData/**/*(except.cs, which are already compile items) andbevel.json.
Example: a CSV loader
A loader can read a CSV of .NET releases with CsvHelper. The loader registers the file because it reads it itself.
using System.Globalization;
using CsvHelper;
public sealed record DotNetRelease(string Version, DateOnly Released, string SupportPhase)
{
// From the recorded phase, not from DateTime.Now.
public bool IsSupported => SupportPhase == "active";
}
public sealed class DotNetReleasesLoader : IBevelDataLoader<IReadOnlyList<DotNetRelease>>
{
public string Name => "Releases";
public Task<IReadOnlyList<DotNetRelease>> LoadAsync(BevelLoadContext context, CancellationToken cancellationToken = default)
{
var path = context.ResolvePath("Data/Releases/dotnet-releases.csv");
context.RegisterInputFile(path); // we read the file ourselves, so register it
using var reader = CsvReader.FromFile(path);
var released = reader.GetFieldIndex("Released");
var releases = new List<DotNetRelease>();
while (reader.Read())
releases.Add(new DotNetRelease(
reader.GetString("Version"),
reader.Parse<DateOnly>(released, CultureInfo.InvariantCulture),
reader.GetString("SupportPhase")));
return Task.FromResult<IReadOnlyList<DotNetRelease>>(releases);
}
}
The output is data.Releases in any page. Types and packages the loader uses must be declared under Data/ or be package references, because the data step compiles only Data/**/*.cs.