Hosting

Hosting

🌍 Idioma: English | Español

Host genérico para aplicaciones Delphi inspirado en Microsoft.Extensions.Hosting de .NET. Compone servicios, configuración, hosted services (workers en segundo plano) y el ciclo de vida de la aplicación en un runtime único y gestionado.

Delphi 12+ Licencia


¿Por qué usarlo?

  • 🏗️ Arranque unificado — Un único lugar para DI, configuración, logging y servicios en segundo plano
  • 🌍 Consciente del entorno — Modos Development / Staging / Production / Testing integrados
  • ⚙️ Configuración por capas — Host config, luego app config, con sobreescritura por variables de entorno
  • 🔄 Hosted services — Registra implementaciones de IHostedService que arrancan y paran con el host
  • 🛑 Apagado eleganteIHostApplicationLifetime señaliza Started, Stopping, Stopped
  • 🔌 Integración con DIIServiceProvider es la columna vertebral; todos los servicios se registran via IServiceCollection

Inicio rápido

uses
  Daf.Hosting,
  Daf.Extensions.Hosting,
  Daf.Extensions.DependencyInjection;

var Host := THostBuilder.Create
  .ConfigureServices(procedure(Context: IHostBuilderContext;
                               Services: IServiceCollection)
  begin
    Services.AddSingleton<IMyService, TMyService>;
    Services.AddHostedService<TMyWorker>; // IHostedService
  end)
  .Build;

Host.Start;
Host.WaitForShutdown;

IHostedService

Cualquier clase registrada como hosted service debe implementar IHostedService:

type
  TMyWorker = class(TInterfacedObject, IHostedService)
  public
    procedure Start;
    procedure Stop;
  end;

procedure TMyWorker.Start;
begin
  // se lanza cuando se llama a Host.Start
end;

procedure TMyWorker.Stop;
begin
  // se llama en el apagado elegante
end;

Registra el worker:

Services.AddHostedService<TMyWorker>;
// equivalente a:
Services.AddSingleton<IHostedService, TMyWorker>;

Entorno

El entorno se lee de la variable DAF_APP_ENV (por defecto Production):

Valor IsDevelopment IsStaging IsProduction IsTesting
Development / deve
Staging / stag
Production / prod
Testing / test
var Env := Host.Services.GetRequiredService<IHostEnvironment>;
if Env.IsDevelopment then
  WriteLn('Modo desarrollo activo');
WriteLn(Env.ContentRootPath);

Variables de entorno leídas al arrancar:

Variable Por defecto Propósito
DAF_APP_ENV Production Nombre del entorno
DAF_APP_NAME Nombre del ejecutable Nombre de la aplicación
DAF_CONTENT_ROOT Ruta del binario Directorio raíz de contenido

Ciclo de vida de la aplicación

var Lifetime := Host.Services.GetRequiredService<IHostApplicationLifetime>;

Lifetime.ApplicationStarted.Register(procedure begin
  WriteLn('App arrancada');
end);

Lifetime.ApplicationStopping.Register(procedure begin
  WriteLn('Parando...');
end);

// Solicitar parada elegante desde cualquier lugar
Lifetime.StopApplication;

Usando TDafApplication (módulo Application)

Para apps de consola, el módulo Application ofrece un wrapper de más alto nivel:

uses DAF.Application.Builder;

TDafApplication.CreateHostBuilder
  .ConfigureServices(procedure(Context: IHostBuilderContext;
                               Services: IServiceCollection)
  begin
    Services.AddSingleton<IMyService, TMyService>;
    Services.AddHostedService<TMyWorker>;
  end)
  .Build
  .Run;

Consulta Application para la documentación completa del módulo Application.


Documentación

  • 📖 Guía de uso — pipeline de configuración, servicios scoped, hosted services, hooks de ciclo de vida

Abstracciones

Hosting.Abstractions

🌍 Idioma: English | Español

Contratos principales del sistema de hosting de DAF. Este módulo define solo interfaces y tipos — sin implementación. Referencíalo cuando escribas hosted services, componentes conscientes del entorno, o extensiones del host genérico sin depender del host concreto.

Delphi 12+ Licencia


Qué hay en este módulo

Todos los tipos se encuentran en Daf.Extensions.Hosting.

Interfaces principales

Interfaz Rol
IHostBuilder Constructor fluido — configura y construye el host
IHost El host en ejecución: Services, Start, Stop, WaitForShutdown
IHostedService Contrato de servicio en segundo plano: Start / Stop
IHostEnvironment Entorno de ejecución: nombre, nombre de app, rutas, IsDevelopment, …
IHostBuilderContext Contexto pasado a los callbacks de configuración: Environment + Configuration
IHostApplicationLifetime Señales de ciclo de vida: ApplicationStarted, ApplicationStopping, ApplicationStopped, StopApplication

Tipos delegado

TConfigureHostConfigAction = TProc<IConfigurationBuilder>;
TConfigureAppConfigAction  = TProc<IHostBuilderContext, IConfigurationBuilder>;
TConfigureServicesAction   = TProc<IHostBuilderContext, IServiceCollection>;

Constantes de entorno

TEnvironments.Development   // 'Development'
TEnvironments.Staging       // 'Staging'
TEnvironments.Production    // 'Production'
TEnvironments.Testing       // 'Testing'

Variables de entorno DAF

TDafEnvVars.APP_ENV       // 'DAF_APP_ENV'
TDafEnvVars.APP_NAME      // 'DAF_APP_NAME'
TDafEnvVars.CONTENT_ROOT  // 'DAF_CONTENT_ROOT'

Helper

IServiceCollectionHelper añade AddHostedService<T> directamente sobre IServiceCollection:

Services.AddHostedService<TMyWorker>;
// equivalente a Services.AddSingleton<IHostedService, TMyWorker>

Dependencias

  • Daf.Extensions.DependencyInjection (DependencyInjection.Abstractions)
  • Daf.Extensions.Configuration (Configuration.Abstractions)
  • Solo RTL de Delphi

La implementación está en Hosting.