jeudi 25 juillet 2019

How do I use reflection to configure all implementations of interface for DI as IOptions<>?

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.





Aucun commentaire:

Enregistrer un commentaire