views:

32

answers:

1

Suppose I want to create a (stateless) WCF service with three methods exposed on an endpoint: performSqlOperationA(), performSqlOperationB(), and performSqlOperationC(). Each method inserts data into a SQL database.

The way I've seen things done at my office, each method would begin with code to initialize a SqlConnection object. Each method would end with code to safely dispose it.

What is a good practice for coding these WCF methods so that the SqlConnection object is initialized and disposed in each method without having to do these things in each method? I know that I can have the connection initialized in the constructor for the class for the WCF methods, but I don't know about disposing it... The calls cannot be wrapped in a using block.

One solution I'm familiar with is PostSharp, which allows me to set an attribute which causes specific code to automatically run at the beginning and end of each method call, but it would be greatly preferable to do this with only the .net framework.

+2  A: 

The best practice is to initialize and dispose the SqlConnection object in each method call (or in a private data access method called from your WCF service operation) with the using statement.

public void performSqlOperationA()
{
    ...
    using(SqlConnection connection = ...)
    {
        ...
    }
    ...
}

What is it that you don't like about this?

Joe
The thing I don't like about this is that I must do it in each method. It seems that there ought to be some way around this redundancy.
Rice Flour Cookies
You can encapsulate various bits (such as getting the connection string and creating the connection), but there isn't a better way to do it. You could also use an ORM, but you will still have an equivalent.
Joe