使用配置生成器时找不到 providerName

No providerName Found When Using Configuration Builder

web.config

<connectionStrings configBuilders="CS_Environment">
   <add name="connectionA" connectionString="EnvVarA" providerName="System.Data.SqlClient"/>
   <add name="connectionB" connectionString="EnvVarB" providerName="System.Data.EntityClient"/>
</connectionStrings>

ConnectionStringSettings 对象的 ProviderName 将是一个空字符串,而不是 "System.Data.SqlClient""System.Data.EntityClient"

NameConnectionString 属性映射就好了。如果我从标签中删除 configBuilders 属性,将填充提供者名称。当然,将不再获取正确的环境变量,但重点是 configBuilder 打破了这一点。

这是用于连接字符串的配置生成器:

<add name="CS_Environment" mode="Greedy" prefix="ConnStr_" stripPrefix="true"
           type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
           Microsoft.Configuration.ConfigurationBuilders.Environment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

目前接受的设置providerName顺序的答案似乎没有任何效果,至少在v2.0中没有。

在v2.0中,问题是由ConnectionStringsSectionHandler中的一个错误引起的,在Greedy模式下完全替换了整个配置元素。

为什么会这样?

这与 Greedy 的工作方式有关:它首先从您的后备存储中获取设置,然后将找到的每个条目添加到配置中。由于bug,for connectionStrings it 实际上确实先删除再添加新的,在此过程中丢失所有额外的属性(包括 providerName)。

解决方法:使用Strict模式

当使用 Strict 模式时,首先查找配置值,找到的每个条目都更新为覆盖值(如果存在)。这意味着原始的 conncetionString xml 节点保留了它的所有属性,包括 prividerName.

修复:实现自定义处理程序

从继承默认 ConnectionStringsSectionHandler 开始,然后修复问题以重用现有的 connectionString(或者只应用适合您需要的 providerName)。

重要的一步是register your app to use your handler over the default one