0

I have ASP.NET Core Web API. I want to inject in DI container IOptions<MySetting> options. In Startup class it injected like this - services.Configure<MySettings>(Configuration.GetSection("MySetting"));. Where MySettings is class with some fields and a section with the same name in appsetings.json.

Also i want inject it with other way. With reflection:

var configureMethod = typeof(OptionsConfigurationServiceCollectionExtensions).GetMethods()
        .Single(m => m.GetParameters().Length == 2)
        .MakeGenericMethod(typeof(MySettings));

I sure configureMethod matches with services.Configure<MySettings>(Configuration.GetSection("MySetting"));.

But when I try to invoke this:

configureMethod.Invoke(null, new object?[] { services, configuration.GetSection("MySettings") });

I get error:

Unhandled exception. System.ArgumentException: Cannot instantiate implementation type 'System.ComponentModel.Design.DesignerOptionService' for service type 'System.ComponentModel.Design.IDesignerOptionService'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate()
...

What am I doing wrong and how to fix it?

hernantos
  • 23
  • 1
  • 5
  • Where are you trying to invoke it? While configuring DI container? Could you please share the code? – Mike Mozhaev Jan 31 '23 at 08:16
  • @MikeMozhaev write in answers. Actually it was problem in searching types, not in calling method with reflection as i thought – hernantos Jan 31 '23 at 08:48

1 Answers1

0

I tried add injecting with reflection for automatically registration {featureNmae}Setting classes in project, because there can be a lot of such classes in project.

In project i have many assemblies and i was getting them for suitable types with AppDomain.CurrentDomain.GetAssemblies() method. Now i change it on Assembly.GetExecutingAssembly() and it works!

hernantos
  • 23
  • 1
  • 5