'Is it possible to inject a specific configuration class bound as a suboption and not to IConfiguration<MyType>?
I have a class that I want injected into some controllers. It has a few dependencies that I want to be automatically injected. Specifically this class requires a configuration object be passed in.
So my appsettings.json file looks something like this:
{
"MyType": {
"Option1": "value"
}
}
And I have a class that mirrors this, ex.
public class MyTypeConfig
{
public string Option1 { get; set; }
}
I have registered this in my startup class.
services.Configure<MyTypeConfig>(Configuration.GetSection("MyType"));
However, I want to receive a "naked" version of MyTypeConfig
in the class being instantiated, NOT IConfigureOptions<MyTypeConfig>
which is what the DI system seems to want to inject.
The constructor for the class being injected looks liked this (which works):
public MySampleClass(IHttpClientFactory httpClient, IConfigureOptions<MyTypeConfig> configuration, ILogger<MySampleClass> logger)
However, this is really want I want:
public MySampleClass(IHttpClientFactory httpClient, MyTypeConfig configuration, ILogger<MySampleClass> logger)
I've looked through the topic on the Microsoft site, here:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2
But I'm not really finding an answer.
How can I just inject the MyTypeConfig?
Solution 1:[1]
Get the class from configuration during startup and register it with the service collection.
MyTypeConfig config = Configuration.GetSection("MyType").Get<MyTypeConfig>();
services.AddSingleton<MyTypeConfig>(config);
Reference Configuration in ASP.NET Core : Bind to an object graph
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nkosi |
Solution 2 | shukebeta |