0

I need to properly Dispose of an object instantiated at request-level scope in my MVC 5 application.

I have declared the object as follows:

<object id="dataContext" singleton="false" scope="request" type="MyDisposableObject, MyAssembly" factory-object="dataContextFactory" factory-method="Build" destroy-method="Dispose" ></object>

<object id="dataContextFactory" scope="application" type="MyFactoryClass, MyAssembly"/>

Code for the DataContextFactory is the following (there is little masking in names)

public class DataContextFactory: DbConfiguration
{

    public IDisposable Build()
    {
        return new Wrapper();
    }

    private class Wrapper : MyDisposableObject //: DbContext
    {
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing); //BREAKPOINT HERE
        }

        public new void Dispose()
        {
            base.Dispose(); //BREAKPOINT HERE
        }
    }
}

This experiment shows me, by placing a breakpoint on the Dispose method, that when I end page request the object (which is ultimately an EF6 DbContext) is not disposed of.

I have read SPRNET-318 but it's kinda ambiguous to me. The bug title is "IDisposable singletons with request or session scopr are not disposed of", which matches my case; however the correlated forum topic says about calling WebApplicationContext.Dispose, which is not my case because I never dispose of the context when the request ends.

Am I missing something on disposing of object at request/session level?

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305
  • Are you using a `using {}` block or calling `Dispose()`. If you are doing neither then no one can say exactly when `Dispose()` will be called and therefore hit your breakpoint –  Jan 30 '15 at 09:30
  • No. I expect Spring to dispose of the object when the request ends. I tried to add a RequestCompleted event to Global.asax to explicitly get and dispose of the object, but this has a drawback: if I never instantiated the object in my request (e.g. it's a CSS request) it will instantiate and dispose of the object – usr-local-ΕΨΗΕΛΩΝ Jan 30 '15 at 09:36

0 Answers0