IoC and dataContext disposing in asp.net mvc 2 application

后端 未结 3 673
北荒
北荒 2021-01-07 00:34

I have the Global.asax like the code below:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(Rou         


        
相关标签:
3条回答
  • 2021-01-07 01:06

    A good place to handle this is in IControllerFactory.ReleaseController, eg

    public override void ReleaseController() {
        base.ReleaseController();
        //Do whatever you need to clean up the IoC container here
    }
    

    In NInject this could be handled by scoping using an activation block, at the start of the request when creating the controller you can store the activation block in the HttpContext's current items, during ReleaseController you can retrieve the previously created activation block and dispose it.

    You could also consider using InScope and having the custom scope implement INotifyWhenDisposed. After that the usage is the same as with an activation block, except now you store the scope in the HttpContext's current items.

    0 讨论(0)
  • 2021-01-07 01:09

    A pattern that is sometimes used to dispose db connections is to call Dispose from the finaliser.

    public class db : IDisposable {
       //called by the garbage collector 
       ~db() {
         //Call dispose to make sure the resources are cleaned up
         Dispose(false);
       }
    
       //IDisposable implementation
       public void Dispose() {
         Dispose(true);
       }
       //subclasses of db can override Dispose(bool) and clean up their own fields
       protected virtual void Dispose (bool disposing) {
         if (disposing) {
           //Supress finalization as all resources are released by this method
           //Calling Dispose on IDisposable members should be done here
           GC.SupressFinalize();
         }
         //Clean up unmanaged resources
         //Do not call other objects as they might be already collected if called from the finalizer
       }
    }
    
    0 讨论(0)
  • 2021-01-07 01:20

    You could hook it into Application_EndRequest.

    0 讨论(0)
提交回复
热议问题