在WCF服务中使用静态DataContext导致错误?

时间:2010-08-10 21:48:20

标签: wcf linq-to-sql

我有一个WCF服务,可以维护与各种数据库的多个连接。我正在使用Linq到Sql Objects。

我采取的方法是在数据库中有一个可用连接列表,当我调用该服务时,我看到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 \我有时会收到错误:“对象引用未设置为对象的实例。”

这是错误的方法,每次打电话给我的服务时是否需要打开连接?

2 个答案:

答案 0 :(得分:1)

不要使用静态DataContext实例。它(以及它具有的SQLConnection)不是线程安全的。

答案 1 :(得分:0)

我更新了我的wcf服务,因此它在每次方法调用时建立了datacontext,看起来这已经解决了我的问题。