Skip to content

Package Development ​

Complete Example: A Discoverable Package Command ​

Create a sibling Acme.Courier class-library project and use the package project file below, with the same DotBlaze version as the consuming app. Delete its generated empty Class1.cs; use this as the package's complete source (an alternative to the extended provider illustration):

csharp
// Acme.Courier/CourierPackage.cs
using DotBlaze;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

[assembly: DotBlazePackage]

namespace Acme.Courier;

public sealed class CourierClient(IConfiguration config)
{
    public string Greeting => config["courier:greeting"] ?? "Hello";
}

public sealed class CourierServiceProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config)
    {
        MergeConfig(config, "courier", new { greeting = "Hello" });
        services.AddSingleton<CourierClient>();
    }
}

public sealed class CourierHelloCommand(CourierClient client) : Command
{
    public override string Signature => "courier:hello {name=world}";
    public override Task<int> Handle()
    {
        Line($"{client.Greeting}, {Argument("name")}.");
        return Task.FromResult(0);
    }
}

From the parent directory containing Blog and Acme.Courier:

shell
dotnet add Blog reference Acme.Courier/Acme.Courier.csproj
dotnet build Blog

Then, from Blog, run dotblaze courier:hello Ada. Expected: Hello, Ada. with no manual provider registration. Setting courier__greeting=Welcome before startup changes it to Welcome, Ada.. Without the assembly attribute, the package's commands/providers are not discovered.

The repository test package extends this pattern with a model and migration. Its package tests verify discovery, config overrides, commands, migrations, and translations.

Introduction ​

Packages are how you add features to DotBlaze. A package can be a small helper library or a whole feature with routes, migrations, views, and commands, like Laravel's packages.

A DotBlaze package is a normal .NET class library. You publish it to NuGet, or to your company's private feed, and the application installs it with dotnet add package. The application does not register anything by hand: DotBlaze finds the package's providers, controllers, migrations, models, commands, listeners, policies, and live components.

Creating a Package ​

Create a class library that references DotBlaze and the ASP.NET Core shared framework:

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <PackageId>Acme.Courier</PackageId>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="DotBlaze" Version="1.1.0" />
  </ItemGroup>

</Project>

Then mark the assembly as a DotBlaze package. Put this line in any file:

csharp
[assembly: DotBlaze.DotBlazePackage]

Discovery ​

When the application starts, it looks for marked assemblies in two places:

  • The application's .deps.json file: every library that depends on DotBlaze.
  • The assemblies the application references, followed transitively.

DotBlaze then scans the marked assemblies the same way it scans the application. Because of the first source, a package is found even if the application never uses one of its types in code.

Assemblies without the attribute are not scanned. This includes DotBlaze's own driver packages, such as DotBlaze.Redis.

Service Providers ​

A service provider is the package's entry point. Providers in a package run with the application's own providers, ordered by full type name:

csharp
using DotBlaze;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Route = DotBlaze.Route;

namespace Acme.Courier;

public sealed class CourierServiceProvider : Provider
{
    public override void Register(IServiceCollection services, IConfiguration config)
    {
        MergeConfig(config, "courier", new { channel = "mail", retries = 3 });
        services.AddSingleton<CourierClient>();
    }

    public override void Boot(WebApplication app)
    {
        Lang.AddNamespace("courier", typeof(CourierServiceProvider).Assembly);
        Route.Get<CourierStatusController>("/courier/status", c => c.Show);
    }
}

Keep the package version aligned with the consuming application. CourierClient and CourierStatusController are package-owned types; a complete executable package containing services, a command, migrations, views, and translations is linked in the complete example.

Resources ​

Configuration ​

MergeConfig gives the package default configuration values, like Laravel's mergeConfigFrom. Call it in Register.

csharp
MergeConfig(config, "courier", new
{
    channel = "mail",
    retries = 3,
    greeting = new { title = "Hello" },   // read as courier:greeting:title
});

These defaults have the lowest priority. The application can override any of them in:

  • its own config/Courier.cs class (CourierConfig : ConfigFile, see Configuration)
  • .env or environment variables (courier__retries=5)
  • command-line arguments

The application's class only needs the keys it changes. Config classes are only discovered in the application assembly, so a package cannot ship one; it gives its defaults with MergeConfig. Read the values with Config.Get("courier.retries") or by injecting IConfiguration.

Publishing Resources ​

All providers use the same Publishes API. New packages with user-customizable configuration must ship a publishable config template and retain runtime defaults through MergeConfig (or existing runtime defaults). Providers without files to customize need not register empty resources. Do not write files during Register or Boot.

Embed the files in the package; .stub templates are UTF-8, while other resources are copied byte-for-byte:

xml
<ItemGroup>
  <!-- Without WithCulture=false, .cs.stub may be treated as a Czech resource. -->
  <EmbeddedResource Include="stubs/*.stub" WithCulture="false"
                    LogicalName="publish/%(Filename)%(Extension)" />
</ItemGroup>

Register manifest resource names and application-relative destination paths in Register:

csharp
public override void Register(IServiceCollection services, IConfiguration config)
{
    MergeConfig(config, "courier", new { channel = "mail", retries = 3 });
    Publishes(services, new Dictionary<string, string>
    {
        ["publish/Courier.cs.stub"] = "config/Courier.cs",
    }, "config", "courier-config");
    services.AddSingleton<CourierClient>();
}

The file stubs/Courier.cs.stub (embedded as publish/Courier.cs.stub) contains:

csharp
using DotBlaze;

namespace {{RootNamespace}}.Configuration;

public class CourierConfig : ConfigFile
{
    public override object Values() => new { channel = "mail", retries = 3 };
}

Use Env("COURIER_API_KEY") for secrets, never a real credential. Keep template defaults aligned with runtime defaults. Use both the shared config tag and a package-specific courier-config tag. Resources such as translations, view overrides, and public assets can use their own tags and destinations through the same API. Migrations are already discovered automatically; do not publish duplicate migration classes.

From the consuming application directory:

shell
# List providers, package assemblies, tags, and destinations; writes nothing.
dotblaze vendor:publish

# Full C# provider name, or package assembly name, or an exact tag.
dotblaze vendor:publish --provider=Acme.Courier.CourierServiceProvider
dotblaze vendor:publish --package=Acme.Courier
dotblaze vendor:publish --tag=courier-config

# Filters combine with AND. --all cannot be combined with filters.
dotblaze vendor:publish --package=Acme.Courier --tag=config
dotblaze vendor:publish --all

# Explicitly overwrite custom files; back them up first.
dotblaze vendor:publish --tag=courier-config --force

dotnet run -- vendor:publish ... also works. A package filter uses the assembly name, which can differ from its NuGet package ID. Unknown filters return exit code 1. Existing files are skipped by default, including when publishing again after an upgrade. --force stages each file before replacing it; a multi-file publish is not a transaction. Conflicting destinations, missing resources, absolute paths, traversal, symbolic links, and junctions are refused before writing.

{{RootNamespace}} is substituted only in .stub resources, from a literal <RootNamespace> in the application's single root .csproj, or its filename when omitted. Set a literal value if your project computes its namespace in imported MSBuild properties. Published C# files and views need a rebuild. Publishing does not change .env or read secrets into generated files.

Built-in templates:

PackageProviderTagOutput
DotBlaze.AIDotBlaze.ArtificialIntelligence.AiServiceProviderai-configconfig/Ai.cs
DotBlaze.HorizonDotBlaze.Horizon.HorizonServiceProviderhorizon-configconfig/Horizon.cs
DotBlaze.PulseDotBlaze.Pulse.PulseServiceProviderpulse-configconfig/Pulse.cs
DotBlaze.TelescopeDotBlaze.Telescope.TelescopeServiceProvidertelescope-configconfig/Telescope.cs

Driver-only packages such as Redis, database drivers, and S3 use the application's existing config sections and have no separate provider template. The generic API is available to every discovered Provider, including application providers and third-party packages; no command changes or hard-coded provider list are needed.

Migrations ​

Migrations in a package run with the application's own migrations, ordered by their [Migration] name. Give them names that describe the package, so they do not collide with the application's migrations:

csharp
[Migration("2026_01_01_000000_create_courier_parcels_table")]
public sealed class CreateCourierParcelsTable : Migration
{
    public override void Up() => Schema.Create("courier_parcels", t =>
    {
        t.Id();
        t.String("code");
        t.Timestamps();
    });

    public override void Down() => Schema.DropIfExists("courier_parcels");
}

Models ​

Models in a package are registered on their connection like the application's own. Their tables follow the usual naming conventions, unless the model sets [Table("...")].

Translations ​

Ship translations inside the assembly as embedded resources, laid out like the application's lang directory:

xml
<ItemGroup>
  <EmbeddedResource Include="lang\**\*.json" LogicalName="lang/%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

Register them in Boot under a namespace. Then use the namespace, followed by ::, in front of the key:

csharp
Lang.AddNamespace("courier", typeof(CourierServiceProvider).Assembly);

Lang.Get("courier::messages.welcome", new { name = "Ada" });   // lang/{locale}/messages.json
Lang.Get("courier::Delivered");                                  // lang/{locale}.json

Use Lang.AddNamespace("courier", directory) to load the translations from a directory instead.

The application can override single lines in lang/vendor/courier. It uses the same layout, for example lang/vendor/courier/id/messages.json. If a line is missing from both the override and the package, it falls back to app.fallback_locale, as usual. See Localization.

Views ​

A view name with a namespace, courier::welcome, means resources/views/vendor/courier/welcome.cshtml. As with other view names, dots separate directories: courier::mail.receipt is vendor/courier/mail/receipt.cshtml.

csharp
return View("courier::welcome", model);

A package ships its views in a Razor class library. Use <Project Sdk="Microsoft.NET.Sdk.Razor"> and add <AddRazorSupportForMvc>true</AddRazorSupportForMvc>, then put the views under resources/views/vendor/courier/.

To customize a view, the application puts its own file at the same path. ASP.NET Core uses the application's view when both exist.

View Components ​

Anonymous components work the same way. <x-courier::alert> renders resources/views/vendor/courier/components/alert.cshtml:

html
<x-courier::alert type="warning">Your parcel is late.</x-courier::alert>

Commands ​

Console commands in a package are added to the application's dotblaze commands and show up in dotblaze list:

csharp
public sealed class CourierPingCommand : Command
{
    public override string Signature => "courier:ping {name=world}";
    public override string Description => "Check the courier service";

    public override Task<int> Handle()
    {
        Info($"pong {Argument("name")}");
        return Task.FromResult(0);
    }
}

Package-specific commands, including make:* generators, must live in the owning package, not in the global CLI. They appear in dotblaze list only when the marked package assembly is installed/discovered. No CLI registration or package-name allowlist is needed. Core generator names (such as make:model) are reserved by the CLI and must not be reused by packages; duplicate application/package command names fail discovery.

For a single-class generator, reuse GeneratorCommand:

csharp
public sealed class MakeCourierLabelCommand : GeneratorCommand
{
    public override string Signature => "make:courier-label {name} {--f|force}";
    public override string Description => "Create a Courier label";
    public override Task<int> Handle() => Generate("app/Courier", "Courier", (ns, name) => $$"""
        namespace {{ns}};

        public sealed class {{name}};
        """);
}

Generate uses the application's root namespace, supports nested names (Shipping/Label), rejects invalid names and unsafe destination paths, and preserves existing files unless --force/-f is passed. It shares namespace and path validation with vendor:publish. Declare {name} and {--f|force} in the signature. More specialized commands can use Command directly.

The CLI runs its core generators locally and forwards other command names to dotnet run -- .... Thus package generators require a buildable application and run provider startup, like migrations and other application commands. They also work with dotnet run -- make:courier-label Shipping.

Controllers, event listeners, policies, and live components in a package are discovered too. Map a package's routes to its controllers from the provider's Boot method, as in the example above.

Testing a Package ​

Test a package in a small host application that references it. Use DotBlaze.Testing to run requests and database assertions against that application.

The framework's own tests use this setup. tests/DotBlaze.TestPackage is a package with a provider, merged configuration, embedded translations, a command, a model, and a migration, and tests/DotBlaze.Tests/PackageTest.cs tests each of them.