【问题标题】:Updating library configuration to work with ASP.NET Core更新库配置以使用 ASP.NET Core
【发布时间】:2016-08-16 12:48:53
【问题描述】:

我们有一个应用程序库,我们想要更新它以与 ASP.NET Core 和以前版本的 ASP.NET 一起使用。此库当前依赖 ConfigurationManager 类从 Web.config 读取设置。随着 ASP.NET Core 中配置的更改,是否有建议的方法来创建一个可以从 ASP.NET Core Web 应用程序和预 ASP.NET Core Web 应用程序读取配置的库?

读取配置设置的当前逻辑示例。

using System.Configuration;

namespace Test.MyLibrary
{
    public class MyLibrarySettings : ConfigurationSection
    {

        private static MyLibrarySettings settings = ConfigurationManager.GetSection("MyLibrarySettings") as MyLibrarySettings;

        public static MyLibrarySettings Settings
        {
            get
            {
                return settings;
            }
        }

        public string SomeSettingValue
        {
            get { return (string)this["someSettingValue"]; }
            set { this["someSettingValue"] = value; }
        }
    }
}

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc asp.net-core


    【解决方案1】:

    对于 ASP.NET Core,您可以直接使用 IConfiguration 的实例,即 表示一组键/值应用程序配置属性:

    public interface IConfiguration
    {
        /// <summary>
        /// Gets or sets a configuration value.
        /// </summary>
        /// <param name="key">The configuration key.</param>
        /// <returns>The configuration value.</returns>
        string this[string key] { get; set; }
    
        ...
    } 
    

    这样你就可以写出类似的代码

        private IConfiguration _configuration;
    
        public string SomeSettingValue
        {
            get { return (string)_configuration["someSettingValue"]; }
            set { _configuration["someSettingValue"] = value; }
        }
    

    请记住,ConfigurationBuilder.Build() 方法返回 IConfigurationRoot,它继承自 IConfiguration

    /// <summary>
    /// Represents the root of an <see cref="IConfiguration"/> hierarchy.
    /// </summary>
    public interface IConfigurationRoot : IConfiguration
    

    【讨论】:

    • 感谢您的回答,但我仍然不清楚这个库是否有办法读取配置设置,无论使用它的 Web 应用程序是使用 ASP.NET 核心还是预 ASP .NET 核心。据我所知,IConfiguation 接口对于 ASP.NET Core 来说是新的,因此它不适用于预 ASP.NET Core 应用程序。可能告诉我我的配置设置不正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多