C# 通过单例类获取数据库连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/814206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting db connection through singleton class
提问by Sharique
I have created an singleton class, this class returns a database connection. So my question is this connection is also satisfying singleton criteria?
If no, than how I can make it singleton.
Here is the code.
我创建了一个单例类,这个类返回一个数据库连接。所以我的问题是这种连接也满足单例标准?
如果没有,那么我如何使它成为单身人士。
这是代码。
public sealed class SingletonDB
{
static readonly SingletonDB instance = new SingletonDB();
static SqlConnection con =new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonDB()
{
}
SingletonDB()
{
}
public static SingletonDB Instance
{
get
{
return instance;
}
}
public static SqlConnection GetDBConnection()
{
return con;
}
}
采纳答案by Chad Grant
Your Singleton is still off.
你的单身人士仍然关闭。
As far as the singleton pattern goes, please see Jon Skeet's very good and detailed description here : http://www.yoda.arachsys.com/csharp/singleton.html
就单例模式而言,请在此处查看 Jon Skeet 非常好的详细描述:http: //www.yoda.arachsys.com/csharp/singleton.html
Using a Singleton for a SqlConnection object is a really, really bad idea. There is no reason to do this whatsoever.
对 SqlConnection 对象使用单例是一个非常非常糟糕的主意。没有理由这样做。
If you are attempting to avoid a performance hit of "new SqlConnection()" or "connection.Open()" be advised that there really is no performance hit there because of the connection pooling going on behind the scenes. Connection Pooling handles the opening/closing of the expensiveconnections. Not the SqlConnection object.
如果您试图避免“new SqlConnection()”或“connection.Open()”的性能下降,请注意那里确实没有性能下降,因为连接池在幕后进行。连接池处理昂贵连接的打开/关闭。不是 SqlConnection 对象。
You won't be able to open multiple SqlDataReaders/Commands with the connection at the same time and will run into thread blocking issues if you are trying to share the same connection object with multiple threads.
您将无法通过连接同时打开多个 SqlDataReaders/Commands,并且如果您尝试与多个线程共享同一个连接对象,将会遇到线程阻塞问题。
The Singleton pattern is the most over used and abused pattern and there are many side effects of the singleton that you may not be aware of. Very good talk about the dangers of singletons here http://www.youtube.com/watch?v=-FRm3VPhseI
单例模式是最被过度使用和滥用的模式,单例模式有很多你可能不知道的副作用。在这里很好地谈论单身人士的危险http://www.youtube.com/watch?v=-FRm3VPhseI
回答by allyourcode
If there's no other way to get a connection to the DB, and if this attribute cannot be overwritten, I would say yes. If that's what you're doing, you're probably taking this singleton thing too far. What if the the DB goes down temporarily and your app loses its connection? Then you'll have to restart your app in order for it to be able to use the DB again.
如果没有其他方法可以连接到数据库,并且无法覆盖此属性,我会说是。如果这就是你正在做的事情,你可能把这个单身事情做得太过分了。如果数据库暂时关闭并且您的应用程序失去连接怎么办?然后,您必须重新启动应用程序才能再次使用数据库。
回答by Fredrik M?rk
I can't answer that question without seeing some code, I think. If you are saying that you will have only one DB connection instance in your application, that might work if you can guarantee that your application will run on only one thread (or at least that all operations using the DB connection does), since you can't (as far as I know anyway) run several operations in parallell on the same connection.
我想,如果没有看到一些代码,我就无法回答这个问题。如果您说您的应用程序中只有一个 DB 连接实例,那么如果您能保证您的应用程序仅在一个线程上运行(或至少所有使用 DB 连接的操作都运行),这可能会奏效,因为您可以't(据我所知)在同一个连接上并行运行多个操作。
Also, if it means that your application will keep the connection open in between uses, I would advise against it. DB connections are limited resources on the DB server, so you should keep them open only when they are needed, and then close them.
此外,如果这意味着您的应用程序将在两次使用之间保持连接打开,我建议您不要这样做。DB 连接是 DB 服务器上的有限资源,因此您应该仅在需要时将它们保持打开状态,然后再关闭它们。
回答by Michael Hedgpeth
The connection itself is not satisfying the Singleton criteria because you can create multiple instances of a database connection object. A singleton by definition can only be instantiated once.
连接本身不满足 Singleton 标准,因为您可以创建数据库连接对象的多个实例。根据定义,单例只能实例化一次。
You canmake the SqlConnection a part of the Singleton, by changing your example to this:
您可以通过将示例更改为以下内容,使 SqlConnection 成为 Singleton 的一部分:
public sealed class SingletonDB
{
private static readonly SingletonDB instance = new SingletonDB();
private readonly SqlConnection con =new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonDB()
{
}
private SingletonDB()
{
}
public static SingletonDB Instance
{
get
{
return instance;
}
}
public SqlConnection GetDBConnection()
{
return con;
}
}
}
This way the SqlConnection used by your SingletonDB class would have one and only one SqlConnection, thus follow the Singleton pattern.
这样,您的 SingletonDB 类使用的 SqlConnection 将只有一个 SqlConnection,因此遵循单例模式。
回答by codeFreak
Singleton means that the class that you have made can be instantiated only once. So if you want that to happen, do two things:
单例意味着您创建的类只能实例化一次。因此,如果您希望发生这种情况,请做两件事:
- Make the constructor private.(This is to prevent other classes from accessing it.)
instantiate the class as:
get { if(instance == null) //important coz, the class will be instantiated only on the first call { instance = new singletonDb; } return instance; }
- 将构造函数设为私有。(这是为了防止其他类访问它。)
将类实例化为:
get { if(instance == null) //important coz, the class will be instantiated only on the first call { instance = new singletonDb; } return instance; }
回答by Egil Andre Greaker
In .NET C# you can wrtie your singleton like this
在 .NET C# 中,您可以像这样写单例
public class Singleton{
public static readonly Singleton Instance= new Singleton();
private Singleton(){}
or for multi threaded environment:
或者对于多线程环境:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}