Web Forms - Contextual Deletion of Objects

I have a .NET 4 web application (Web Forms) that uses the Entity Framework to manage data using a MySQL database. For each page, I create a context for this model in Page_Load.

 string connString = ConfigurationManager.ConnectionStrings["dbconnection"].ToString();
 MyModel = new MyEntities(connString);

Now in the next steps on the page, I can use MyModel to retrieve and update data. This is clean and simple for me, but I always assumed that .NET had canceled the previous MyModel page when a new page request was made. I understand that this may not be so? and memory can be used inefficiently.

I saw a good inclusion example using (MyEntities MyModel = new MyEntities (ConfigurationManager.ConnectionStrings["dbconnection"].ToString()))that handles deletion, but it doesn't seem clean if I have 6+ actions on the page, each of which needs to recreate the context when called (not what my current method does better).

Is there a way to create a context once on the initial page load and get rid of it when a new page is called, a non-postback is called, or a user session ends?

+4
source share
2 answers

You can override the virtual Disposemethod System.Web.UI.Control and manage your context there:

public override void Dispose()
{
  if (MyModel != null)
    MyModel.Dispose();
  base.Dispose();
}

, MyModel , :

private MyEntities fMyModel = null;

protected MyEntities MyModel
{
  get
  {
    if (fMyModel == null)
    {
      string connString = ConfigurationManager.ConnectionStrings["dbconnection"].ToString();
      fMyModel = new MyEntities(connString);
    }
    return fMyModel;
  }
} 

Dispose :

public override void Dispose()
{
  if (fMyModel != null)
    fMyModel.Dispose();
  base.Dispose();
}

, Page Dispose - .

+5

Dispose() Unload .

protected void Page_Unload(object sender, EventArgs e)
{
    MyModel.Dispose();
}

, , , - ( , WebForms MVC . IoC, ​​ Ninject.

0

All Articles