开发者

Singleton Pattern / Check for Null - While using Asp.Net with Session

In the below code i want the "GetClassTeacher" method to be executed only once per session in Asp.net application, I have used session to check whether the object is null before calling the database.

My question is, Is this the best way to implement this method or can i use singleton pattern to accomplish this, If so how to implement it per session.

public class School
{
   public  List<Student> GetAllStudents() {}

  public 开发者_运维问答 List<Teacher>  GetAllTeachers() {}    

  //Singleton pattern or Check for Null
  public Teacher GetClassTeacher()
   {
       Teacher  teacher = new Teacher();
       teacher = Session["Teacher"] as Teacher
       if (teacher == null)
       {
            //Get Teacher Info from Database
       }   
   }
}


I think using session is fine-- but you can cut down on some of the overhead by not instantiating a teacher object if you don't have to:

   public Teacher GetClassTeacher()
   {
       var teacher = Session["Teacher"] as Teacher
       if (teacher == null)
       {
            //Get Teacher Info from Database
       }   
   }


Checking for null is perfectly valid. Using Session is also valid.

    public static Teacher GetClassTeacher()
    {
        Teacher teacher = HttpContext.Current.Session["Teacher"] as Teacher;
        if (teacher == null)
        {
            //Get Teacher Info from Database
            teacher = GetTeacherFromDB();
            HttpContext.Current.Session["Teacher"] = teacher;                
        }
        return teacher;
    }


Here's a sample of singleton: http://msdn.microsoft.com/en-us/library/ff650316.aspx. And also, some investigation into different implementations: http://www.yoda.arachsys.com/csharp/singleton.html.

Otherwise, I'm not sure how to say if it's "best" to use a singleton (or not to use one). Your situation will help determine it. Personally, I don't find much need for it in what I do in asp.net.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜