Skip to content

02. Bootstraping

ogoun edited this page Apr 23, 2026 · 2 revisions

Bootstrapping

Bootstrap is the canonical entry point for any long-running ZeroLevel-based service. It wires up logging, configuration and the network stack, and gives you a fluent API to shape the host.

Minimum console service

using ZeroLevel;

class Program
{
    static void Main(string[] args)
    {
        Configuration.Save(Configuration.ReadFromApplicationConfig());

        Bootstrap.Startup<MyService>(args,
                () => Configuration.ReadSetFromIniFile("config.ini"))
            .EnableConsoleLog(
                ZeroLevel.Services.Logging.LogLevel.System |
                ZeroLevel.Services.Logging.LogLevel.FullDebug)
            .UseDiscovery()                              // optional — enables service discovery
            .Run()                                       // start the service
            .WaitWhileStatus(ZeroServiceStatus.Running); // block main thread until Stop

        Bootstrap.Shutdown();                            // flush logs, close sockets, dispose
    }
}

Implementing a service

Every service inherits from BaseZeroService and overrides StartAction / StopAction:

public sealed class MyService : BaseZeroService
{
    protected override void StartAction()
    {
        Log.Info("MyService is starting up");
        // init: network host, schedules, background loops
    }

    protected override void StopAction()
    {
        Log.Info("MyService is stopping");
        // cleanup: cancel loops, close files
    }
}

Hosting a network endpoint

Inside StartAction, expose handlers through UseHost():

protected override void StartAction()
{
    var router = UseHost(8800);                 // bind TCP on port 8800

    router.RegisterMessageHandler<Ping>((client, msg) =>
        Log.Info($"ping from {client.EndPoint}"));

    router.RegisterRequester<PingRequest, PongResponse>((client, req) =>
        new PongResponse { Ts = DateTime.UtcNow });
}

See 07. Network for the full TCP surface.

Windows service (with Topshelf)

ZeroLevel composes cleanly with Topshelf to host the same service as a Windows Service:

IServiceExecution se = null;
Configuration.Save(Configuration.ReadFromApplicationConfig());

HostFactory.Run(x =>
{
    x.StartAutomatically();
    x.Service<BootstrapFluent>(s =>
    {
        s.ConstructUsing(_ => Bootstrap.Startup<MyService>(args)
            .EnableConsoleLog(LogLevel.FullDebug));
        s.WhenStopped(fluent => { fluent.Stop(); Bootstrap.Shutdown(); });
        s.WhenStarted(fluent => { se = fluent.Run(); });
    });
    x.RunAsLocalSystem();

    x.SetDescription("MyService");
    x.SetDisplayName("MyService");
    x.SetServiceName("MyService");

    x.OnException(ex => Log.Error(ex, "Service exception"));
});

if (Environment.UserInteractive)
{
    se?.WaitWhileStatus(ZeroServiceStatus.Running);
}

Fluent builder API

Bootstrap.Startup<T>(...) returns a BootstrapFluent:

Method Effect
.EnableConsoleLog(LogLevel) Attach a console logger.
.EnableFileLog(path, options) Attach a rolling text-file logger.
.EnableEncryptedFileLog(options) Attach an encrypted file logger.
.UseDiscovery() / .UseDiscovery(url) / .UseDiscovery(IPEndPoint) Register the service with a discovery hub.
.Run() Start the service; returns IServiceExecution.
.Stop() Stop the service (when invoked on the BootstrapFluent).

Lifecycle summary

  1. Load configuration (from app.config / ini / args).
  2. Configuration.Save(...) — make it the process default.
  3. Bootstrap.Startup<TService>(args, () => ...) — construct the host.
  4. Chain .EnableXxxLog(...) / .UseDiscovery() — attach cross-cutting concerns.
  5. .Run().WaitWhileStatus(ZeroServiceStatus.Running) — block main thread.
  6. Bootstrap.Shutdown() — tear everything down (logs, network, schedulers).

Clone this wiki locally