C # uses singleton mode for database connectivity

Source: Internet
Author: User
Tags oracleconnection

1. Using Assembly Oracle.ManagedDataAccess.dll

Using Oracle.ManagedDataAccess.Client;
Using System.Configuration;

Namespace ClassLibrary1
{
///


Database connection Practice single-instance mode
///
public class Oracledbconect
{
private static oracleconnection con = null;
private static Object obj = new Object ();
///
Define public static property instance, external call
///
public static OracleConnection Instance
{
Get
{
When the first thread runs here, the locker object is "locked" at this point,
When the second thread runs the method, it first detects that the locker object is a "lock" state, and the thread suspends waiting for the first line threads unlocked
After the lock statement finishes running (that is, after the thread finishes running) The object is "unlocked"
Double locking requires just one sentence.
if (con==null)
{
Lock (obj)
{
if (con==null)
{
var str = configurationmanager.connectionstrings["Dbcontection"]. connectionstring;//getting the database connection string in the configuration file
con = new OracleConnection (str);//instantiation
Try
{
Con. Open ();
}
catch (Exception e)
{
return null;
}
}
}
}
return con;
}
}

    // 私有构造函数是一种特殊的实例构造函数。它通常用在只包含静态成员的类中。    // 如果类具有一个或多个私有构造函数而没有公共构造函数,则其他类(除嵌套类外)无法创建该类的实例。    //声明空构造函数可阻止自动生成默认构造函数,因为当编译器看到我们的类中没有定义构造函数时,编译器会帮我们生成一个公有的无参构造函数。    //注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。    // 但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化。    private oracledbconect() { }}

}

C # uses singleton mode for database connectivity

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.