kkoziarski
kkoziarski

Reputation: 121

ASP.NET Core - how to inject IOptionsMonitor<T[]>

How can I inject IOptionsMonitor<T[]> into a controller?

In appsettings.json

{
      "MyArray": [
       {
          "Name": "Name 1",
          "SomeValue": "Value 1",
       },
       {
          "Name": "Name 2",
          "SomeValue": "Value 2",
       }
      ]
}

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddOptions();
     services.Configure<MyOptions[]>(Configuration.GetSection("MyArray"));
}

In HomeController

public class HomeController : Controller
{
    private readonly MyOptions[] myOptions;
    public HomeController(IOptionsMonitor<MyOptions[]> myOptions)
    {
        this.myOptions = myOptions.CurrentValue;
    }
}

I'm getting Unable to resolve service for type 'Microsoft.Extensions.Options.IOptionsMonitor`1[MyOptions[]]' while attempting to activate 'Api.Controllers.HomeController'. exception.

I can access the configuration by configuration.GetSection("MyArray").Get<MyOptions[]>() and it works, but I would like to inject it as constructor parameter.

Upvotes: 4

Views: 8068

Answers (2)

Muhamed Karajic
Muhamed Karajic

Reputation: 63

Late but might be helpful for someone else, just use the

services.Configure<List<string>>(configuration.GetSection("Parrent:Array"));

appsettings.json example:

{
   "Parent": {
       "Array": ["A", "B", "C"]
   }
}

Upvotes: 1

Kahbazi
Kahbazi

Reputation: 15015

You need to create a class with MyOptions[] as a property and the inject that class and add the whole configuration without section.

public class Options
{
    public MyOptions[] MyArray { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddOptions();
     services.Configure<Options>(Configuration);
}

HomeController.cs

public class HomeController : Controller
{
    private readonly MyOptions[] myOptions;
    public HomeController(IOptionsMonitor<Options> myOptions)
    {
        this.myOptions = myOptions.CurrentValue.MyArray;
    }
}

Upvotes: 5

Related Questions