How to release HybridHttpOrThreadLocalScoped objects in StructureMap?
Asked Answered
C

1

9

When performing background tasks in a Windows Service I used HybridHttpOrThreadLocalScoped for storing intances of NHibernate ISessions.

Since within a Windows Server there isn't a HTTPContext, I'm wondering if only calling the ReleaseAndDisposeAllHttpScopedObjects() is enough to release the ISession instance for that thread?

Coaming answered 21/6, 2011 at 11:39 Comment(2)
Have you tried this? What was the result?Homogeneous
I didn't think it was. I just gave it a try and got a NullReferenceException which I'm guessing is because there isn't a HttpContext. So No, that method is definitely not the right way to release the session.Coaming
C
15

I found out how to answer this question. The ReleaseAndDisposeAllHttpScopedObjects() method exposed by the ObjectFactory is really concerned with the HttpContext and therefore web applications.

The HybridLifeCycle class from the Structuremap.Pipeline namespace allows to directly access cached objects inside the ThreadLocal storage and dispose them. Here is an example:

Action.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<UnitOfWork>();

Above code registers the supplied type and caches its instances in the HttpContext or the ThreadLocal storage. It's always a good idea to inherite those types from IDisposable. Thus in this example UnitOfWork is also an IDisposable.

new HybridLifecycle().FindCache().DisposeAndClear();

Now to dispose cached objects regardsless of a web application or windows service the above line is sufficient to dispose the UnitOfWork instead of the ReleaseAndDisposeAllHttpScopedObjects() method. I hope this helps someone.

Coaming answered 23/6, 2011 at 5:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.