开发者

static object to access database - asp.net

开发者 https://www.devze.com 2023-02-16 13:38 出处:网络
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

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 c开发者_StackOverflowall 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


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.


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.


It depends on what you're doing inside the methods.

If, within the method, you open a new connection, use it, and dispose of it, you're fine. No harm, no foul. So long as you're not maintaining state, you're good to go.

On the other hand, if you're maintaining state, you've got problems, as thread-safety enters the picture. In that case, you're much better off just creating a class that's designed to be instantiated.


I would advice static class, if you see small number of concurrent users querying the Static class.A static class can easily handle sufficient requests serially (say a 20 + in a second). The database routine is more likely bottleneck, depending on the query.

Take care of thread safety**

0

精彩评论

暂无评论...
验证码 换一张
取 消