我收到错误“底层提供程序在打开时失败”。最近,我一直在拔头发试图找出原因。仔细检查错误,内部异常是“连接未关闭。连接的当前状态为正在连接。” 堆栈跟踪是
"at System.Data.ProviderBase.DbConnectionClosedConnecting.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)"
据我所知,错误似乎是随机发生的,或者可能是在对应用程序进行更改时发生的。任何帮助将不胜感激。
我目前的设置是
- IIS 快递
- Microsoft SQL Server 速成版
- 视觉工作室 2012
- MVC Web API \ Asp.net MVC 4
- 实体框架 5
我的数据层是根据存储库模式建模的,并通过结构图注入。
存储库
public class Repository<T> : IDisposable, IRepository<T> where T : class
{
private readonly DbSet<T> _dbSet;
private readonly DbContext _dbContext;
public Repository(IDbContextFactory<MyContext> dbContextFactory)
{
_dbContext = dbContextFactory.Create();
_dbSet = _dbContext.Set<T>();
}
//removed for brevitity
public void Dispose()
{
_dbContext.Dispose();
}
数据库上下文工厂
public class MyContextFactor : IDbContextFactory<MyContext>, IDisposable
{
private MyContext _dataContext;
public MyContextFactor Create()
{
return _dataContext ?? (_dataContext = new MyContext());
}
public void Dispose()
{
_dataContext.Dispose();
}
}
IOC 结构图注册表
For(typeof(IDbContextFactory<MyContext>)).HybridHttpOrThreadLocalScoped().Use(typeof(MyContextFactory));
连接字符串
<add name="MyContextConnectionString" connectionString="metadata=res://*/Model.MyProject.csdl|res://*/Model.MyProject.ssdl|res://*/Model.MyProject.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=MyDB;User Id=SQLUser;Password=****;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
我试图解决问题但到目前为止还没有奏效的事情
- 通过结构映射范围确保上下文是每个 http 上下文
- 将 dispose 添加到存储库
- 向 ContextFactory 添加了 dispose
- 从集成 Sql 身份验证切换到 Sql 身份验证