Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static object to access database - asp.net

Tags:

c#

asp.net

Hi I am developing a web site I have a class which is the connection to data base The class consists a methods that write and read from the data base Currently, the class is static and also its methods I call the class from web pages like that:

//mydbClass is the name of the class , not an object
mydbClass.getUserName(userID) 

The question is: Do I need to create a class object, so that each time user asking for a page a new object is created and it communicates with the data base , like that:

mydbClass mydb = new mydbClass();
mydb.getUserName(userID)

Because if I do not create a new object So all the users that read or write to the data base Will use the same static object, then it will be very busy and perhaps it will collapse I'd love an answer Thanks micha

like image 950
micha Avatar asked Aug 15 '26 01:08

micha


2 Answers

If you want to keep using your class a bit like a static class but with a state , you can implement the singleton pattern

http://en.wikipedia.org/wiki/Singleton_pattern

public class mydbClass{ 
    private static mydbClass  _current = new    mydbClass(); 
    public static mydbClass Current{
        get{
            return _current;
        }
    } 
    private mydbClass(){} 
    public User getUserName(userid){
    //be sure to create a new connection each times
    }
}

The advantage here is that you can simply implement interface in this class, break dependencies and then mock it for testing purpose.

Anyway, you'll always have to create a new connection at each request do not create a static connection object.

like image 198
remi bourgarel Avatar answered Aug 17 '26 16:08

remi bourgarel


You definitely should not use a static class for the connections. If you use a static class then you have to worry about being thread safe because of all the threads using the same class to talk to the database. Just create new database connections each time, and use connection pooling. Connection pooling will make creating new connections each time much faster.

like image 23
Zach Green Avatar answered Aug 17 '26 15:08

Zach Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!