Question

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.

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top