Dependency Injection
CobaltPdf integrates with the ASP.NET Core / Microsoft.Extensions.DependencyInjection container via a single extension method.
Registration
In Program.cs (or Startup.cs), call AddCobaltPdf on the service collection:
using CobaltPdf.Extensions;
using CobaltPdf.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCobaltPdf(o =>
{
// Use a CloudEnvironment preset — applies the right flags and pool sizing
CloudEnvironment.ConfigureForDocker(o);
// Override individual values as needed
o.MaxSize = Math.Max(2, Environment.ProcessorCount);
});
var app = builder.Build();
This registers CobaltEngine as a singleton — one shared instance backed by the global browser pool for the lifetime of the application.
Tip
Choose the preset that matches your deployment target:
CloudEnvironment.ConfigureForLinux— Linux VM or bare-metalCloudEnvironment.ConfigureForDocker— Docker containerCloudEnvironment.ConfigureForAzure— Azure App Service / Functions Premium PlanCloudEnvironment.ConfigureForAwsEcs— AWS ECS / FargateCloudEnvironment.ConfigureForLowMemory— memory-constrained (AWS Lambda, small containers)
Graceful Shutdown
Register a shutdown hook so Chromium processes are terminated cleanly when the application stops:
var app = builder.Build();
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
CobaltEngine.ShutdownAsync().GetAwaiter().GetResult());
app.Run();
Injecting CobaltEngine
Inject CobaltEngine into any service or controller via the constructor:
public class ReportService
{
private readonly CobaltEngine _renderer;
public ReportService(CobaltEngine renderer)
{
_renderer = renderer;
}
public async Task<byte[]> GenerateInvoicePdfAsync(int invoiceId)
{
var pdf = await _renderer
.WithMetadata(m =>
{
m.Title = $"Invoice #{invoiceId}";
m.Author = "Billing System";
})
.RenderUrlAsPdfAsync($"https://myapp.internal/invoices/{invoiceId}/print");
return pdf.BinaryData;
}
}
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
private readonly CobaltEngine _renderer;
public PdfController(CobaltEngine renderer)
{
_renderer = renderer;
}
[HttpGet("report")]
public async Task<IActionResult> GetReport(CancellationToken cancellationToken)
{
var pdf = await _renderer
.RenderUrlAsPdfAsync("https://myapp.internal/report/print", cancellationToken);
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
}
Thread Safety
CobaltEngine is designed to be used as a singleton. Its per-render state (_pendingOptions) is protected by an internal lock, so multiple concurrent requests can safely call fluent methods and render simultaneously. Each render acquires its own browser lease from the pool and runs in its own isolated browser context.
Logging Integration
Forward browser console messages to ILogger:
builder.Services.AddCobaltPdf(o => { /* pool config */ });
// After building the app, hook into the logging pipeline
var logger = app.Services.GetRequiredService<ILogger<Program>>();
CobaltEngine.OnBrowserLog = message =>
logger.LogDebug("[Chromium] {Message}", message);
Licensing
Call SetLicense before app.Run():
CobaltEngine.SetLicense(builder.Configuration["CobaltPdf:LicenseKey"]!);
Or read from an environment variable:
CobaltEngine.SetLicense(Environment.GetEnvironmentVariable("COBALTPDF_LICENSE")!);
Complete Program.cs Example
using CobaltPdf;
using CobaltPdf.Configuration;
using CobaltPdf.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Register CobaltPdf with a cloud preset
builder.Services.AddCobaltPdf(o =>
{
CloudEnvironment.ConfigureForDocker(o); // Docker-ready flags & pool sizing
o.MaxSize = Math.Max(2, Environment.ProcessorCount); // scale with available CPUs
});
var app = builder.Build();
// Activate license
CobaltEngine.SetLicense(app.Configuration["CobaltPdf:LicenseKey"]!);
// Pre-warm the pool
await CobaltEngine.PreWarmAsync();
// Forward browser console logs to ILogger
var logger = app.Services.GetRequiredService<ILogger<Program>>();
CobaltEngine.OnBrowserLog = msg => logger.LogDebug("[Chromium] {Msg}", msg);
// Graceful shutdown
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
CobaltEngine.ShutdownAsync().GetAwaiter().GetResult());
app.MapControllers();
app.Run();