ASP.NET Core document conversion with dependency injection

One call, AddDocToolkit(), registers DocToolkit with ASP.NET Core dependency injection. This guide covers the install, the settings, background services and tests.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDocToolkit();

var app = builder.Build();

Install and register

  • The extensions package brings the core package with it, so you do not need to reference both.
  • One call registers all 21 interfaces the package ships, each a thin wrapper over the matching static class.
  • An interface differs from its static class only by the leading I: IPdfEditor wraps PdfEditor.
  • All are singletons, which is safe because none of them holds state.
  • They are registered with TryAdd, so your own implementation, registered first, wins.

Set it once

  • DocToolkitOptions holds application-wide settings, so they are not repeated at every call site.
  • AllowRemoteImageDownload is the master switch for remote images. It is false unless you set it.
  • Page sets the paper once. The default is PageSetup.A4.
  • A call that names a page still wins over the configured one.
  • Options are read on each call, not once at startup. A change in appsettings.json with reloadOnChange takes effect on the next conversion, with no restart.

Background services and tests

  • A BackgroundService can take these services straight in its constructor, because they are stateless singletons.
  • Wrapping them in a scope would imply a lifetime problem that is not there.
  • In a test, substitute the interface, for example IHtmlToPdfConverter, so the test does not spend time rendering a real PDF.
  • Tests about the conversion itself should call the real thing. It needs no fixtures and no network.

What it will not do

  • The extensions package adds no capability. Everything it exposes is available statically; it exists for substitutability and configuration.
  • For a console app, a script or a library, use Ank.DocToolkit and call the static classes.