SqlConnection 单例 [英] SqlConnection Singleton

查看:52
本文介绍了SqlConnection 单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想问一下,创建 Singleton 以仅与 db 建立一个活动连接是否是个好主意.我想做的是:1) 我有 wcf 服务2)wcf服务从db获取数据3)我想创建一个这样的单例,只有一个连接到数据库:

Greetings, I would like to ask if creating Singleton to have only one active connection to db is a good idea. What i would like to do is: 1) I have a wcf service 2) wcf service gets data from db 3) i would like to create a singleton like this to have only one connection to db:

private static PersistanceSingleton _Instance;
    public static PersistanceSingleton Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = new PersistanceSingleton();
            }
            return _Instance;
        }
    }

我知道这不是一个理想的单身人士,但我只是为了这篇文章而写的.我想在这里有一些持久性存储库,我将在构造函数中实例化它们.在我的服务类中,我将在构造函数中包含以下代码

I know this is not an ideal singleton but i just wrote it for this post purpose. I would like to have some persistance repositories here and which I will be instantiating them in constructor. Inside my service class I would have the following code inside constructor

_DBPersistanceSingleton = PersistanceSingleton.Instance;

然后当一些请求出现时(例如 GetUsersRequest)我想做一些类似的事情:

Then when some request comes (e.g. GetUsersRequest) i would like to do something like:

_DBPersistanceSingleton.GetUsers()

在每次调用 db 之前,我还会检查 SqlConnection 是否打开.请让我知道这是否是一个好习惯.我之所以考虑这个解决方案是因为大量用户将通过客户端应用程序连接到该服务

Before each call to db is executed I will also check whether SqlConnection is open or not. Please let me know if this is a good practice. The reason why I think about this solution is because of large number of users that will be connecting to that service via client application

推荐答案

像这样重用 SqlConnection 不是一个好习惯.需要时打开它,用完后立即关闭.连接池将在重用连接的情况下为您工作.

It's not a good practice to reuse SqlConnection like that. Open it when you need it and close it as soon as you're done with it. Connection pooling will work for you under the hood reusing the connection.

这篇关于SqlConnection 单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆