DbProviderFactories.GetFactory(providerClass)没有看到刚刚安装的提供程序

时间:2012-10-15 16:39:41

标签: .net dbproviderfactories

如果我在应用运行时安装了提供商。然后调用DbProviderFactories.GetFactory(providerClass)来查看它是否已安装,我得到一个异常调用它。但是,如果我退出我的应用并重新启动它,那么就会看到它。

我需要调用什么才能让DbProviderFactories.GetFactory(providerClass)重新读取machine.config?

1 个答案:

答案 0 :(得分:2)

首次使用时,会在静态数据表中读取提供程序信息,然后始终返回该值,直到应用程序重新启动,并且该数据表当然会再次重新创建。

以下代码(首次在Windward Wrocks发布)将刷新内部缓存并强制重新读取:

/// <summary>
/// Force DbProviderFactories to re-read machine.config on the next call to
/// DbProviderFactories.GetFactoryClasses().
/// </summary>
static public void FlushDbProviderFactoriesCache()
{
  try
    {
    FieldInfo initStateFieldInfo = typeof(DbProviderFactories).GetField("_initState",
                                  BindingFlags.Static | BindingFlags.NonPublic);
    if (initStateFieldInfo != null)
      {
        ConnectionState state = ConnectionState.Closed;
        object initState = initStateFieldInfo.GetValue(state);
        if (initState is ConnectionState)
        {
          state = (ConnectionState)initState;
          if (state != ConnectionState.Closed)
            initStateFieldInfo.SetValue(state, ConnectionState.Closed);
          ConfigurationManager.RefreshSection("system.data");
        }
      }
    }
  catch (Exception)
    {
    // nada
    }
  }