I have a DocumentRenderer class, which calls an external API. The DocumentRenderer requires an AccessKey, which is stored in my appsettings.json config file. I want a newly instantiated DocumentRenderer object to, by default, use the AccessKey specified in the config file. However, I can't figure out how to achieve this outside of startup.cs. (I'm using ASP.NET Core)
Here's what I've tried so far:
Added DocumentRenderer to appsettings.json:
"DocumentRenderer": {
"AccessKey": "<key>",
"EndpointUrl": "<url>",
"OutputFormat" : "pdf"
}
Created a "DocumentRendererOptions" POCO:
public class DocumentRendererOptions
{
public string AccessKey { get; set; }
public string EndpointUrl { get; set; }
public string OutputFormat { get; set; }
}
Registered DocumentRendererOptions as a singleton service and bound the options from appsettings.json to it in the ConfigureServices method of startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<DocumentRendererOptions>();
services.Configure<DocumentRendererOptions>(options => Configuration.GetSection("DocumentRenderer").Bind(options));
}
Finally I have my DocumentRenderer class:
public class DocumentRenderer
{
private readonly string _endpointUrl;
private readonly string _accessKey;
private readonly string _outputFormat;
public DocumentRenderer()
{
}
public DocumentRenderer(IOptions<DocumentRendererOptions> options)
{
_accessKey = options.Value.AccessKey;
_endpointUrl = options.Value.EndpointUrl;
_outputFormat = options.Value.OutputFormat;
}
}
I incorrectly assumed this would allow me to instantiate a new DocumentRenderer object with the default options, but obviously something is missing.
Every article I've read so far just talks about using this method with a controller and allowing DI to do the rest, but the DocumentRenderer isn't a controller.
As a temporary fix I've just made DocumentRendererOptions static, then assigned the values in startup, but this doesn't seem like the best solution