1

Introduction

I'm using IOptions<> in ASP to provide configuration to services. Currently I have to setup each POCO individually. I would like to do this in a generic way.

I would like to use some sort of reflection to automaticly configure all POCO's that are used for configuration injection with IOptions. Thus avoiding calling the services.Configure<Poco>() for each class.

The working setup

My appsettings.json file.

{
  "DemoOption": {
    "OptionOne": "hello",
    "OptionTwo": "world"
  }
}

POCO for configuration section:

public class DemoOption
{
    public string OptionOne { get; set; }
    public string OptionTwo { get; set; }
}

Enables me to do this:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<DemoOption>(configuration.GetSection(nameof(DemoOption)));
}

And use it like this:

public class MyService
{
    public IOptions<DemoOptions> _options { get; set; }

    public MyService(IOptions<DemoOptions> options)
    {
        _options = options;
    }
}

What I've got this far

To use reflection I create and add an IOption interface to my POCO class:

public class DemoOption : IOption // Added empty IOption interface
{
    public string OptionOne { get; set; }
    public string OptionTwo { get; set; }
}

This is where I'm stuck. I've gotten all the implementations of the IOptions interface, but I can't figure out how to call the services.Configure() method.

public void ConfigureServices(IServiceCollection services)
{
    // This actually works and finds all implementations.
    var options = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(x => x.GetTypes())
        .Where(x => typeof(IOption).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
        .Select(x => x).ToList();

    // This does not work
    foreach (var o in options)
    {
        // What should I write here?
        services.Configure<o>(configuration.GetSection(nameof(o)));
    }
}

All help appriciated.

  • Your question boils down to just how to call `Configure` via reflection, which is covered in the linked answer. – Chris Pratt Jul 25 '19 at 15:13

1 Answers1

0

Configure is a generic method so the type can only be evaluated at compile time.

There is no member available accepting instance of Type as a parameter in IServiceCollection reference.

Another option would be to use a reflection to generate many more generic methods at runtime, it can work in the case but the approach itself is not quiet fast.

Artyom Ignatovich
  • 591
  • 1
  • 3
  • 13