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:IPdfEditorwrapsPdfEditor. - 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
DocToolkitOptionsholds application-wide settings, so they are not repeated at every call site.AllowRemoteImageDownloadis the master switch for remote images. It isfalseunless you set it.Pagesets the paper once. The default isPageSetup.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.jsonwithreloadOnChangetakes effect on the next conversion, with no restart.
Background services and tests
- A
BackgroundServicecan 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.DocToolkitand call the static classes.
Install
dotnet add package Ank.DocToolkit.Extensions.DependencyInjectionRead it in the DocToolkit docsNuGetGitHub