How to release HybridHttpOrThreadLocalScoped objects in StructureMap?

二次信任 提交于 2019-12-21 04:04:48

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6424629/how-to-release-hybridhttporthreadlocalscoped-objects-in-structuremap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!