Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-webapi

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.


Solution

  • 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;
        }
    }