1

I would like to change my Startup class to scan the system for all the classes that implement an interface and then register them automatically. I'm using Scrutor just to make life easier.

Normally, this is simple to achieve with code similar to this:

services.Scan(scan => scan
    .FromAssemblyOf<ISomething>()
    .AddClasses()
    .AsImplementedInterfaces()
    .WithTransientLifetime());

My problem is that I can't do this with the options-pattern.

I normally have something like this in my startup:

services.Configure<GatewaySettings>(
    options => _config.GetSection(nameof(GatewaySettings)).Bind(options));

Which allows me to inject the class into a constructor like this:

public Something( IOptions<GatewaySettings> myOptions)
{
   use(myOptions.Value);
}

Is there a way (using Scrutor would be nice, but I'm open to other suggestions) to register all my options-classes. I can easily identify them in the codebase either by naming convention or by decorating them with an empty interface. My issue is that I don't know how to call "services.Configure()" with the scanned classes.

I'm effectively looking for some way of achieving this:

services.Configure(, myScannedType,
    options => _config.GetSection(myScannedType.GetName()).Bind(options));
Steven
  • 166,672
  • 24
  • 332
  • 435
  • 2
    You will have to implement this yourself by iterating the `ServiceCollection`, inspecting the constructors of all registrations and the required `Configure` calls yourself. Nothing exists OOTB in ASP.NET Core nor Scrutor that will help you with that. – Steven May 19 '21 at 10:01

1 Answers1

1

You can use reguto library to register all appsettings auto.

Usage:

[Options("GatewaySettings")]
public class GatewaySettings
{
    //your properties
}

Register services

public void ConfigureServices(IServiceCollection services)
{
    services.AddReguto();
    services.ConfigureReguto(Configuration);
}

Nuget

Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
  • 1
    Thanks Farhad. This works beautifully. It's also good as an example of how to do this yourself. The code is actually not all that complex. – Mulciber Coder May 21 '21 at 10:46