[英]How to call DI Confgure<T>(Config) with reflection?
我有 ASP.NET Core Web API。我想注入 DI 容器IOptions<MySetting> options
。 在Startup
class 中,它像这样注入 - services.Configure<MySettings>(Configuration.GetSection("MySetting"));
. 其中MySettings
是 class ,其中包含一些字段和一个在appsetings.json
中具有相同名称的部分。
我也想用其他方式注入它。 反思:
var configureMethod = typeof(OptionsConfigurationServiceCollectionExtensions).GetMethods()
.Single(m => m.GetParameters().Length == 2)
.MakeGenericMethod(typeof(MySettings));
我确定configureMethod
与services.Configure<MySettings>(Configuration.GetSection("MySetting"));
匹配 .
但是当我尝试调用它时:
configureMethod.Invoke(null, new object?[] { services, configuration.GetSection("MySettings") });
我收到错误:
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()
...
我做错了什么以及如何解决?
我尝试在项目中添加反射注入以自动注册{featureNmae}Setting
类,因为项目中可能有很多这样的类。
在项目中,我有很多程序集,我正在使用AppDomain.CurrentDomain.GetAssemblies()
方法为合适的类型获取它们。 现在我在Assembly.GetExecutingAssembly()
上更改它并且它有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.