如果我在应用运行时安装了提供商。然后调用DbProviderFactories.GetFactory(providerClass)来查看它是否已安装,我得到一个异常调用它。但是,如果我退出我的应用并重新启动它,那么就会看到它。
我需要调用什么才能让DbProviderFactories.GetFactory(providerClass)重新读取machine.config?
答案 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
}
}