Reputation: 531
I am aware of constructor pattern to get to a configured IOptions e.g.
public SomeClass(IOptions<SomeOptions> someOptions)
{
}
However, I have run into a scenario where I have an existing method where I want to access SomeOptions. I do not want to change the signature for the constructor of that class. Is there any other way to access SomeOptions?
Upvotes: 2
Views: 1701
Reputation: 9946
This is the "service locator" anti-pattern, but you can retrieve services from the DI container within controllers or any of the other base classes that give you an instance of HttpContext
:
var opts = HttpContext.RequestServices.GetService(typeof(IOptions));
Upvotes: 2
Reputation: 49789
Built-in DI container in ASP.NET Core is very simple and supports dependency injection only via constructor. In your case, you have 2 options (as you don't want to change the ctor signature)
IOptions<SomeOptions>
as the argument to your existing method
. But you will need to get options from DI container in some other place before calling the method though. Upvotes: 0