【发布时间】:2010-08-10 21:48:20
【问题描述】:
我有一个 WCF 服务,它维护与各种数据库的多个连接。我正在使用 Linq 到 Sql 对象。
我采用的方法是,我在数据库中有一个可用连接列表,当我调用服务时,我会查看 DataContext 是否已经存在,如果不存在,我会创建一个新的 DataContext
private static Dictionary<String, GenericDataClassesDataContext> _db = new Dictionary<string,GenericDataClassesDataContext>();
private bool AddConnection(string applicationName, string connectionString)
{
try
{
//Test Connection
SqlConnection testConn = new SqlConnection(connectionString);
testConn.Open();
string commandString = "Select * from ModelEntity";
SqlCommand sqlCmd = new SqlCommand(commandString, testConn);
SqlDataReader dataReader = sqlCmd.ExecuteReader();
//if exists remove
if (_db.ContainsKey(applicationName))
_db.Remove(applicationName);
//add connection
_db.Add(applicationName, new GenericDataClassesDataContext(connectionString));
_db[applicationName].ObjectTrackingEnabled = false;
return true;
}
catch
{
return false;
}
}
private bool CheckConnection(string applicationName)
{
try
{
if (!_db.ContainsKey(applicationName))
{
_genericConnection.Open();
SqlCommand thisCommand = new SqlCommand("GetConnection", _genericConnection);
thisCommand.CommandType = CommandType.StoredProcedure;
thisCommand.Parameters.Add(
new SqlParameter("@Name", applicationName));
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
string conString = thisReader[1].ToString();
if (AddConnection(applicationName, conString) == false)
return false;
}
thisReader.Close();
}
return true;
}
finally
{
if (_genericConnection != null)
{
_genericConnection.Close();
}
}
}
调用示例
public ReferenceValue[] GetReferenceValues(string applicationName)
{
if (CheckConnection(applicationName))
return _db[applicationName].ReferenceValues.ToArray();
return null;
}
(在我看到的大多数示例中,都会为每个服务调用创建新的 DataContext,所以我现在认为我可能存在严重的设计缺陷)
我遇到的问题是
A\当 WCF 应用程序中发生错误时,我的连接似乎“中断”了后续调用(至少有一段时间)
B\ 我有时会收到错误返回:“对象引用未设置为对象的实例。”
这是错误的做法吗,每次调用我的服务时我都需要打开连接吗?
【问题讨论】:
标签: wcf linq-to-sql