DI Support for the HTML/CSS to Image API client.
$ dotnet add package HtmlCssToImage.DependencyInjection
This package provides dependency injection support for the HtmlCssToImage client.
Add the package to your project:
dotnet add package HtmlCssToImage.DependencyInjection
IHtmlCssToImageClient in your application's startupProgram.cs or Startup.cs)You can provide your API Id and Key directly or using standard dotnet Configuration.
If you want to provide your API Id and Key directly, you can do so by calling AddHtmlCssToImage in your Program.cs or Startup.cs - this may be useful for testing purposes locally, but it is not recommended to use plain text credentials in your source code in production.
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHtmlCssToImage("api_id", "api_key");
}
}
To provide your API Id and Key using an action, you can call AddHtmlCssToImage in your or and pass in an action that will be invoked to retrieve your API Id and Key.
Program.csStartup.cspublic class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHtmlCssToImage(options =>
{
options.ApiId = Environment.GetEnvironmentVariable("HCTI_API_ID")!;
options.ApiKey = Environment.GetEnvironmentVariable("HCTI_API_KEY")!;
});
}
}public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHtmlCssToImage(builder.Configuration.GetSection("HCTI"));
}
}You can also simply pass a string to the AddHtmlCssToImage method to bind to a configuration section.
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHtmlCssToImage("HCTI");
}
}In either case, your configuration would look like this:
{
"HCTI":{
"ApiId": "api_id",
"ApiKey": "api_key"
}
}See HtmlCssToImageOptions.cs for the Configuration object
Because the HtmlCssToImage client is added to the DI container as a typed HTTP Client (see Microsoft Docs) it means you can extend its default behavior, such as adding retry policies or logging.
All the .AddHtmlCssToImage() methods return an IHttpClientBuilder which allows you to configure the underlying HttpClient instance.
This library is built with performance in mind and is fully compatible with Native AOT (Ahead-of-Time) compilation in .NET 9+.
The client internally uses source-generated JSON serialization, so no extra configuration is required for standard API requests.
The configuration binding source generator is enabled, so you can safely use the IConfiguration overload of AddHtmlCssToImage without any additional configuration. You still need to ensure that the PublishAot flag is enabled in your project file.
[!IMPORTANT] Check out the HTML/CSS To Image Docs for more details on the API's capabilities.
[!TIP] Get started for free at htmlcsstoimage.com.