schauhan
schauhan

Reputation: 531

ASPNET Core 2.0: Is there a way to access IOptions without constructor pattern?

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

Answers (2)

McGuireV10
McGuireV10

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

Set
Set

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)

  • setup and use any other DI container that supports dependency injection via method/property etc
  • or pass 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

Related Questions