简体   繁体   中英

How to define Sqlconnection Globally in asp.net c#

I have defined connectionstring in web.config like this

<add name="connect" connectionString="Initial Catalog=MyDatabase;User ID=sa;Password=mypassword" />

So I have to create Sqlconnection in each page inside class like this

SqlConnection cn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connect"].ConnectionString);

I don't want to create SqlConnection in each page. Is there any way to create sqlconnection only once and use it in every page ?

there are two ways:

1) Create BasePage class which has the code to create the connection in it... this will work best if you need a different connection for every user/session instance.

2) Create a static class with an initialize method and call it to the connection created and initialized on application_start

Here's an example of the static class with the application_Start

public static class Connections
{
     public static SqlConnection Connection {get; set;}
     public static Init()
     {
         //INIT YOUR CONNECTION PROPERTY HERE
         //Connection = new SqlConnection(....);
     }

}

IN GLOBAL.ASAX

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    Connections.Init();
}

then in any ASP.Net back-end code you can reference/access it directly.

Connections.Connection

This is valid for the entire lifetime of the web application (Start to End)

You can achieve this desire output by

public class ConnectionHandler
{
    static SqlConnection con=null;
    public static SqlConnection ConnectionObj 
    {
        get
        {
         if(con==null)
             con=new SqlConnection("your connection string");
        return con;
     }
}

Latter on you can use this connection object like this

SqlConnection con=ConnectionHandler.ConnectionObj; 

是的,你可以将其存储里面Application作为字典Application["Connection"] = cn

private static void Main(string[] args)
    {

        Services.Container.AddService(typeof(DbConnectionHandler),new DbConnectionHandler("connectionstring"));
        Services.Container.AddService(typeof(MyClass), new MyClass((DbConnectionHandler)Services.Container.GetService(typeof(DbConnectionHandler))));

        var myclass = (MyClass)Services.Container.GetService(typeof (MyClass));
        Console.WriteLine($"servicecontainertest {myclass.Testshit()}");

        Console.ReadLine();
    }

    public static class Services
    {
        public static ServiceContainer Container { get; set; }
        static Services()
        {
            Container = new ServiceContainer();
        }
    }

    class MyClass
    {
        private DbConnectionHandler _dbHandler { get; set; }
        public MyClass(DbConnectionHandler dbhandler)
        {
            _dbHandler = dbhandler;
        }

        public string Testshit()
        {
            return _dbHandler.Connection.ConnectionString;
        }
    }
    class DbConnectionHandler
    {
        public SqlConnection Connection { get; set; }
        public DbConnectionHandler(string connection)
        {
            Connection = new SqlConnection(connection);
        }
    }

As you can see in my example i create a Global Service Class that contains a Servicecontainer, then adding Dbconnection to it, i can access it by using Services.Container.GetService() anywhere i want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM