0

I have the following code that is being copied and pasted in a number of places. The only difference being that there is a single call in the middle of the usings which changes. So I made a

public MyEntity Read(int id)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return MyDataLayer.Select(sqlConn, id);
    }
}

So I came up with this. However, my problem is how do i pass the sqlConn var to the call?

public TResult UsingSqlConnection<TResult>(Func<TResult> myFunction)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return myFunction();
    }
}

public MyEntity Read(int id)
{
    return UsingSqlConnection(() => MyDataLayer.Read(id)); 
   //PROBLEM: Read() requires sqlConn
}

Off the top of my head - it looks like instead of passing it as a param, that I need to create a property for SqlConn in MyDataLayer and assign it in the UsingSqlConnection method using an interface. While i wont rule out that refactor, I am wondering if I am missing something as this is my first attempt with Func delegates in this way.

1 Answer 1

4

Func can have parameters:

public TResult UsingSqlConnection<TResult>(Func<SqlConnection, TResult> myFunc)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return myFunc(sqlConn);
    }
}

public MyEntity Read(int id)
{
    return UsingSqlConnection((sqlConn) => MyDataLayer.Read(sqlConn, id));       
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.