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
csharp
[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:

csharp
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, BevelLoadContext and ILogger<T>.
  • Each loader runs in its own scope.
  • Configuration follows WebApplication.CreateBuilder. See Build environment.
  • Prebuild compiles Data/**/*.cs on its own, using your project's global usings (including the SDK's implicit usings), LangVersion, Nullable and DefineConstants. 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 newer Microsoft.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*Async helpers (ReadJsonAsync, ReadYamlAsync, ReadMarkdownAsync, ReadXmlAsync and their directory variants) are tracked automatically.
  • A file you read yourself needs context.RegisterInputFile(path). Use RegisterInputDirectory for a folder whose listing you read, and RegisterRecursiveInputDirectory when you read it recursively, so added and removed files count too.
  • Databases and APIs cannot be tracked. Set BevelPrebuildAlwaysRun to true so 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.
csharp
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-incremental and rebuilds also run it.
  • dotnet watch watches Data/**/* (except .cs, which are already compile items) and bevel.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.

csharp
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.