dododo
dododo

Reputation: 4897

Asp.net Core. Configure IOptions method with Type params (not generic)

Is there a way to call the method Configure from IServiceCollection DI container with non generic params?

I want to register my config section not like the following:

services.Configure<AppSection>(Configuration);

But in this way:

services.Configure(typeof(AppSection), Configuration);

I want to do this as I want to pass my config sections by List<Type> collection from low-level application levels(DAL) to High-level (Web api). And then make only a loop by this collection with registration each section.

foreach (var type in LowAppLevelSections)
{
   services.Configure(type, Configuration);
}

So, in the end I will not have strong dependency between for example DAL and Web API level.

Is there any idea?

Upvotes: 2

Views: 830

Answers (1)

nomail
nomail

Reputation: 650

Here's an approach. All you have to do is clean it up a bit, write some unit tests. (Again sorry for the messy code)

public static class IServicesCollectionExtension
{
    public static IServiceCollection Configure(this IServiceCollection services, Type typeToRegister, IConfiguration service)
    {
        var myMethod = typeof(OptionsConfigurationServiceCollectionExtensions)
          .GetMethods(BindingFlags.Static | BindingFlags.Public)
          .Where(x => x.Name == nameof(OptionsConfigurationServiceCollectionExtensions.Configure) && x.IsGenericMethodDefinition)
          .Where(x => x.GetGenericArguments().Length == 1)
          .Where(x => x.GetParameters().Length == 2)
          .Single();

        MethodInfo generic = myMethod.MakeGenericMethod(typeToRegister);
        generic.Invoke(null, new object[] { services, service });
        return services;
    }
}

Upvotes: 2

Related Questions