DbProviderFactories.GetFactory(providerClass) does not see just installed provider

StackOverflow https://stackoverflow.com/questions/12900107

  •  07-07-2021
  •  | 
  •  

Вопрос

If I install a provider while my app is running. And then call DbProviderFactories.GetFactory(providerClass) to see if it is installed, I get an exception calling it. But if I exit my app and the re-start it, then it sees it.

What do I have to call to get DbProviderFactories.GetFactory(providerClass) to re-read machine.config?

Это было полезно?

Решение

The provider information is read in static data table when first time used and then that value is always returned until application restarts and that data table is of course again re-created.

The following code (first published at Windward Wrocks) will flush that internal cache and force a re-read:

/// <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
    }
  }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top