【问题标题】:Load Custom ConfigSection in ASP.NET Core Application在 ASP.NET Core 应用程序中加载自定义 ConfigSection
【发布时间】:2018-01-22 22:29:28
【问题描述】:

我们有一个新的 ASP.NET Core 2.0 应用程序,但我们需要使用 .NET Framework 4.6.1 库,该库需要访问 Web.config(或类似)中定义的自定义 ConfigSection .初始尝试导致错误,表明内部组件无法加载/找到该部分。这在非核心应用程序中运行良好,我们希望有一种方法可以在核心中实现这一点。

这是一个如何在配置文件中注册的示例。

<configSections>
    <section name="data-connector" type="Connector.Configuration.ConnectorConfigSection, Connector" />
</configSections>

如果有帮助,组件将使用以下代码加载其配置部分。

/// <summary>
/// Loads an instance of a specified configuration section or a default instance if one was not found
/// </summary>
/// <typeparam name="T">The Configuration Section type to be loaded</typeparam>
/// <param name="sectionName">The name/path of the section to be loaded as seen in the config file</param>
public static T GetSectionInstance<T>(string sectionName) where T : ConfigurationSection
{
    if (string.IsNullOrEmpty(sectionName)) throw new ArgumentNullException("sectionName");

    var instance = (ConfigurationSection)ConfigurationManager.GetSection(sectionName);

    return (instance == null || !typeof(T).IsAssignableFrom(instance.GetType()))
            ? Activator.CreateInstance<T>()
            : instance as T;
}

我们可以要求组件所有者对其加载过程进行更改,但我们不能将其设为原生核心组件。

是否有解决方法来确保仍然可以支持 web.config 部分?

【问题讨论】:

  • 你可以访问设置文件源代码(通常由VS生成)吗?如果是,也许您可​​以将其移植到 .NET Core?加载逻辑应该很基本吧?
  • 抱歉 Meikel,这不是我们的选择。

标签: c# asp.net-core


【解决方案1】:

如果您在 .NET Framework 上使用 ASP.NET Core 2.0,则需要使用 app.config 而不是 web.config。

【讨论】:

    【解决方案2】:

    您可以在Startup.ConfigureServices 中使用 DI 容器添加配置或其部分,并将其注入控制器或服务女巫将使用您的库。

    【讨论】:

    • 我们很乐意这样做,但我们不明白如何做到这一点。可以提供样品吗?
    • docs.microsoft.com/en-us/aspnet/core/fundamentals/… 应该可以帮助您在 .Net Core 中开始使用 DI
    • 请阅读这里:stackoverflow.com/questions/39231951/… 之后您所需要的一切。是将您的配置传递给您的类库中的注入位置和使用位置。
    • 这似乎不能回答 OP 的(完全合理的)问题,至少不是没有例子。我已经阅读了您发布的链接(在评论中),但它似乎并没有具体涵盖实现这一目标的必要条件。请在答案本身中添加有关如何使这项工作(如果知道)的详细信息。 DI 将是答案如果组件供应商可以这样做,但如果组件希望从自定义配置部分获取设置,这可能不起作用。
    【解决方案3】:
    Just create an App.config like below. Working in ASP.NET Core.
    <configuration>
      <configSections>
        <section name="EmailConfig" type="MyApp.Handler,MyApp">
      </configSections>
      <EmailConfig to = "to@test.com" from="from@test.com"
        subject="test" body ="" />
    </configuration>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-14
      • 2019-12-16
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多