Static object to access the database - asp.net

Hi. I am developing a website. I have a class that is a database connection. The class consists of methods that write and read from the database. Currently the class is static, as well as its methods. I call the class from web pages as follows:

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

Question: I need to create a class object so that every time a user requests a page a new object is created and it communicates with the database as follows:

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

Because if I do not create a new object in this way, all users who read or write to the database will use the same static object, then it will be very busy and maybe it will crash. I would like the answer thanks to Micah

+3
source share
4 answers

If you want to use your class a bit like a static class, but with state, you can implement a singleton template

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 is that you can simply implement the interface in this class, break the dependencies and then mock it for testing purposes.

In any case, you always need to create a new connection with every request, do not create a static connection object.

+2
source

. , , , . . .

+1

, .

, , . , . , .

, , , . , .

+1

I would recommend a static class if you see a small number of concurrent users requesting a Static class. A static class can easily handle sufficient requests one at a time (say 20 + per second). Depending on the request, the database procedure is rather a bottleneck.

Take care of thread safety **

0
source

All Articles