7

I wanted to be sure if structuremap will dispose my DataContext after per request ends.

Here is my setup

ForRequestedType<MyDataContext>().TheDefault.Is.OfConcreteType<MyDataContext>();
SelectConstructor<MyDataContext>(() => new MyDataContext());

Will structuremap auto dispose my datacontext or do i need to call Dispose manually??

Petrick Lim
  • 287
  • 4
  • 13

2 Answers2

9

That's what I do:

    For<IUnitOfWork>()
        .HybridHttpOrThreadLocalScoped()
        .Use<BpReminders.Data.NH.UnitOfWork>();

    For<ISession>()
        .HybridHttpOrThreadLocalScoped()
        .Use(o => ((BpReminders.Data.NH.UnitOfWork)o.GetInstance<IUnitOfWork>()).CurrentSession);

and ...

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

HybridHttpOrThreadLocalScoped uses the HttpContext when available.

StructureMap looks after everything, then. Just remember to implement IDisposable in your classes.

LeftyX
  • 35,328
  • 21
  • 132
  • 193
  • Though in SM using HybridHttpOrThreadLocalScoped will use ThreadLocal storage, calling ReleaseAndDisposeAllHttpScopedObjects throws an exception. Can you tell me how you've managed to dispose objects stored in ThreadLocal? – Roman Jun 23 '11 at 04:26
  • @Am: You can't use HybridHttpOrThreadLocalScoped is a member of HttpContextLifecycle. I've seen that ThreadLocalStorageLifecycle (which is the one you're interested in) has got a method called EjectAll. I've never used it, thought, and never really dig into this. – LeftyX Jun 23 '11 at 08:31
4

No it will not Dispose it automatically, unless you use nested containers and Dispose the container holding the context instance. It's up to the creator of the context to Dispose it. The creator would usually be the part of your code calling ObjectContext.GetInstance<MyDataContext> or the root method that makes StructureMap inject a DataContext into one of your objects.

A common practice is to create a context per HttpRequest and dispose the context at the end of the request.

PHeiberg
  • 29,411
  • 6
  • 59
  • 81