如果我在应用程序运行时安装提供程序。然后调用 DbProviderFactory.GetFactory(providerClass) 查看它是否已安装,我收到调用它的异常。但是,如果我退出我的应用程序并重新启动它,那么它就会看到它。
我必须调用什么才能让 DbProviderFactories.GetFactory(providerClass) 重新读取 machine.config?
首次使用时,在静态数据表中读取提供程序信息,然后始终返回该值,直到应用程序重新启动,当然会再次重新创建该数据表。
以下代码(首次发布于 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
}
}