Looking for a way to register IOptions<> with an interface and separate concrete type

Using Microsoft DI framework along with MS Options and MS Configuration.

I am trying to call IServiceCollection.Configure<>() to expose an interface but bind to a specific concrete class. This can be done with IServiceCollection.AddSingleton<>(), but not with Configure. I'm looking for a solution

Here is an example of what I want

//config objects
interface IConfigPoco {
    IReadonlyList<string> Names { get; }
}
class ConfigPoco : IConfigPoco {
   private List<string> Names { get; set; }
   IReadonlyList<string> IConfigPoco.Names => Names;
}

//registration
//this is the part that does not work
//Configure<IConfigPoco, ConfigPoco> does not exist
var services = new ServiceCollection();
services.Configure<IConfigPoco, ConfigPoco>(configSection)

//injection
public ctor(IOptions<IConfigPoco> poco) {
     //poco.Value.GetType() == typeof(ConfigPoco)
}

This works, but I'd like to have all IOption[Special]<> types registered as well

_ = services
    .AddSingleton<IOptions<IConfigPoco>, IOptions<ConfigPoco>>((sp) =>
    {
        var poco= new ConfigPoco();
        config
           .GetSection(nameof(ConfigPoco))
           .Bind(poco, (b) => { b.BindNonPublicProperties = true; });

        var opt = Options.Options.Create(poco);
        return opt;
    });

Is there a library that handles this or is there an easy way to manually register IOptionsMonitor<> and IOptionsSnapshot<>?

Posted Jan 3, 2021, 9:25 AM UTC

38
SalizarMarxx•

At what point would you expect a configuration class to be different is so that you would want/allow multiple inherited instances from a common interface?

The reason that this doesn’t support the same type inputs as AddSingleton is simply that configuration classes shouldn’t be referenced as interfaces.

6
Prod_Is_For_TestingOP•

I showed the use case I have in mind. It’s not about having multiple concrete classes. I want to use interface segregation to hide “raw” parsed members and only expose “filtered” members. So here, I want to expose IReadOnlyList, but obviously that can’t be parsed from JSON, so my concrete class needs a real list to bind to.

A common solution is to use private properties that align with the JSON types and then expose a different property that maps to the type that you want. I have found that this can be difficult to work with because the compiler will optimize out the private property and the binder will have nowhere to write the values

1
Ttxman•

I don't think compiler will remove (optimize away) private fields, properties and methods from classes.

I am 100% sure that unused private methods will not get removed. The given reason was unexpected behavior when using reflection. I assume removing any private thing from class will result in "unexpected behavior when using reflection" so they also should not be removed..

2
grauenwolf•

The AOT compiler might remove it. But that's not a valid reason for such a strange design pattern.

0
Prod_Is_For_TestingOP•

It might be strange, but I’m forced to work with what’s available for config files. There are a lot of types that either can’t be expressed in JSON or can’t be bound by the options binder. You have to get “creative” to load those values when needed

1
Ttxman•

If you don't mind also having IOptions<ConfigPoco> in your services, you can just proxy it as your subconfiguration interfaces.

 _ = services.AddTransient<IOptions<IConfigPoco>>(sp => sp.GetRequiredService<IOptions<ConfigPoco>>());

You can wrap the proxying in helper method to proxy all configuration variants

internal static IServiceCollection AddSubConfig<IT, T>(this IServiceCollection sc) where T : class, IT where IT : class
        {
            sc.AddSingleton<IOptions<IT>>(sp => sp.GetRequiredService<IOptions<T>>());
            sc.AddTransient<IOptionsSnapshot<IT>>(sp => sp.GetRequiredService<IOptionsSnapshot<T>>());
            sc.AddSingleton<IOptionsMonitor<IT>>(sp => sp.GetRequiredService<IOptionsMonitor<T>>());
            return sc;
        }

Then just add your proxy interface:

_ = services.AddSubConfig<IConfigPoco, ConfigPoco>();

You can even do some code generator magic to create method that will add all sub config interfaces automatically (Or just use reflection). In the end you can end up with something like:

_ = services.AddSubConfigurations();

To hide the ConfigPoco from developers :p, you can move the configuration into separate assembly. Then you declare the interfaces as public, config classes as private. Make static helper method in which you call all your Configure<...> and AddSubConfig<...,...>. Then call the helper method from configure.

You will still be able to get the config_class service by iterating all services and filtering by type name, but without reflection you can't do anything with it. And with reflection you can get the the same class from the config_interface service even when the config_class service is not registered

1
Prod_Is_For_TestingOP•

Yeah that’s a good idea. I was leaning towards something like that. Thanks

1