Using dependency injection in a non-controller class?

对着背影说爱祢 提交于 2019-12-13 15:21:19

问题


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


回答1:


register the DocumentRenderer with services as well so the framework will instantiate it for you

public void ConfigureServices(IServiceCollection services)
{
    // Adds services required for using options.
    services.AddOptions();

    // Registers the following lambda used to configure options.
    services.Configure<DocumentRendererOptions>(Configuration.GetSection("DocumentRenderer"));

    //register other services
    services.AddSingleton<DocumentRenderer>();
}

Source: Using Options and configuration objects



来源:https://stackoverflow.com/questions/41591704/using-dependency-injection-in-a-non-controller-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!