开发者

What is a good practice for handling SQL connections within a WCF call?

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 can开发者_如何转开发not 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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜