当前位置: 首页 > 编程语言 > C#

在.NETCore2.0中将配置绑定到对象图Share

时间:2023-04-10 22:17:56 C#

Bindingconfigurationtoanobjectgraphin.NETCore2.0我正在查看此文档,似乎在.NETCore1.0中你可以这样做:varappConfig=newAppSettings();config.GetSection("App").Bind(appConfig);在.NETCore1.1中,您可以:varappConfig=config.GetSection("App").Get();但是Bind也不存在于.NETCore2.0中。实现这一目标的新方法是什么?谢谢,开玩笑你仍然可以两者兼顾。由于您在控制台应用程序中,因此可能没有使用ASP.NETCore元数据包,因此您需要确保具有正确的依赖项。要将配置绑定到对象,您需要Microsoft.Extensions.Configuration.Binder包。那么这两种解决方案都应该可以正常工作。顺便一提。即使您在控制台应用程序中,您仍然可以使用ASP.NETCore附带的依赖项注入容器。我个人觉得它很容易设置,所以如果你仍然可以修改你的应用程序来使用它,那可能是值得的。设置将如下所示:varconfiguration=newConfigurationBuilder().AddJsonFile("config.json",optional:false).Build();varservices=newServiceCollection();服务.AddOptions();//在这里添加你的服务services.AddTransient();服务.AddTransient();//配置选项services.Configure(configuration.GetSection("App"));//构建服务提供者varserviceProvider=services.BuildServiceProvider();//检索主应用程序实例并运行程序varprogram=serviceProvider.GetService();程序.运行();然后所有注册的服务都可以像在ASP.NETCore中一样使用依赖项。然后,为了使用您的配置,您可以注入IOptions类型,如IOptions.直到今天我终于弄明白了,我仍然遇到这个问题。代码运行没有问题,但所有属性仍然为null,即使在绑定之后也是如此。我这样做:publicclassAppSettings{publicstringMyProperty}结果你必须这样做:publicclassAppSettings{publicstringMyProperty{get;放;它只有在你的类有属性而不是字段时才有效。我不清楚。如果要在启动期间注册配置,请将其添加到Startup.cs:services.Configure(Configuration.GetSection("App"));然后,您可以通过注入IOptions的实例来访问它:privatereadonlyAppSettings_appSettings;publicMyClass(IOptionsappSettings){_appSettings=appSettings.Value;为了更容易配置,我创建了一个辅助类,它扫描配置对象的嵌套配置,然后尝试在加载的程序集中找到相应的类,并使用给定的配置对其进行初始化。appsettings.json:{"MyState":{"SomeSimpleValue":"HelloWorld","MyTimeSpan":"00:15:00"}}MyStateOptions.cs//类与appsettings.json同名,带有Options后缀。publicclassMyStateOptions{//属性必须可从字符串中反序列化//或者具有默认构造函数的类//只有可从字符串中反序列化的属性。公共字符串SomeSimpleValue{得到;放;}publicDateTimeMyTimeSpan{get;放;}}Startup.cspublicclassStartup{publicIConfigurationRootConfiguration{get;}publicStartup(IHostingEnvironmentenv){//根据需要创建配置...varbuilder=newConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile(...).AddEnvironmentVariables();//将配置保存在属性中以便稍后访问它。配置=builder.Build();}publicvoidConfigureServices(IServiceCollectionservices){//注册所有你想要的服务...services.AddMvc(op选项=>...);//调用我们的辅助方法services.RegisterOptions(Configuration);}}HelperClass.cspublicstaticclassIServiceCollectionExtensions{publicstaticvoidRegisterOptions(thisIServiceCollectionservices,IConfigurationconfiguration){//从给定的配置创建所有选项。varoptions=OptionsHelper.CreateOptions(配置);foreach(varoptioninoptions){//我们返回Options:IOptionsvarinterfaces=option.GetType().GetInterfaces();foreach(vartypeininterfaces){//注册选项IServiceCollectionservices.AddSingleton(type,option);}}}}OptionsHelper.cspublicstaticclassOptionsHelper{publicstaticIEnumerableCreateOptions(IConfigurationconfiguration){//获取所有对象部分:varsections=configuration.GetChildren().Where(section=>section.GetChildren().任何());foreach(varsectioninsections){//如果没有完成,添加“选项”后缀。varname=section.Key.EndsWith(“选项”)?section.Key:section.Key+"选项";//扫描AppDomain以查找匹配的类型。vartype=FirstOrDefaultMatchingType(名称);if(type!=null){//使用ConfigurationBinder使用给定数据创建实例。varsettings=section.Get(类型);//在“选项”中封装实例varoptions=CreateOptionsFor(settings);}}}privatestaticTypeFirstOrDefaultMatchingType(stringtypeName){//查找具有默认构造函数的匹配类型returnAppDomain.CurrentDomain.GetAssemblies().Where(assembly=>!assembly.IsDynamic).SelectMany(assembly=>assembly.GetTypes()).Where(type=>type.Name==typeName).Where(type=>!type.IsAbstract).Where(type=>type.GetMatchingConstructor(Type.EmptyTypes)!=null).FirstOrDefault();}privatestaticobjectCreateOptionsFor(objectsettings){//调用泛型方法Options.Create(TOptionsoptions)varopenGeneric=typeof(Options).GetMethod(nameof(Options.Create));变种方法=openGeneric.MakeGenericMethod(settings.GetType());returnmethod.Invoke(null,new[]{settings});完成所有这些之后,您可以在服务集合中拥有一个服务,该服务在其构造函数中具有一个函数,需要一个IOptions并且您无需显式配置每个选项即可获得它,您只需使用该服务创建一个新项目和您想要的选项实例。将项目添加到主项目中,并在appsettings.json中添加需要的配置。ExampleService.cs以上是C#学习教程:.NETCore2.0中绑定配置到对象图。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——publicclassMyExampleService{privatereadonlyMyStateOptions_options;publicMyExampleService(IOptionsoptions){_options=options?.Value??抛出新的ArgumentNullException(名称(选项));管理员删除。如需转载请注明出处: