ServiceStack, Structuremap 3 and disposing HybridHttpOrThreadLocalScoped intances

202 views
Skip to first unread message

Anton Kallenberg

unread,
Jun 30, 2014, 10:46:37 AM6/30/14
to servic...@googlegroups.com
Hello Guys,

I want to use one single open IDbConnection through each request and by the end of each request close and dispose the connection. To keep the code DRY if want StrucureMap to do this for me.

When configuring ServiceStack I register my repositories as HybridHttpOrThreadLocalScoped:

container.Configure(x => x.For(typeof(IRepository<>)).HybridHttpOrThreadLocalScoped().Use(typeof(Repository<>)));

In my app host I override OnEndRequest and call DisposeAndClearAll to make sure that all HybridHttpOrThreadLocalScoped-instances are disposed:

 public override void OnEndRequest()
        {
            if (HttpContextLifecycle.HasContext())
            {
                HttpContextLifecycle.DisposeAndClearAll();
            }
            base.OnEndRequest();
        }

My repositories implements IDisposable and disposes the IDbConnection:

 public virtual void Dispose()
        {
            if (db == null)
            {
                return;
            }
             db.Dispose();
        }

but unfortunately the IDbConnection is not disposed and I'm running out of the connection quite fast :)

Am I missing something or do you suggest a different approach? 

Regards,
Anton

RR

unread,
Dec 23, 2014, 4:31:33 PM12/23/14
to servic...@googlegroups.com
Anton,

Did you find the solution to this? I'm dealing with the exact same situation right now. I'm calling HttpContextLifecycle.DisposeAndClearAll(); in my Application_EndRequest() method and it's not calling Dispose on my objects that implement IDisposable. They are registered with StructureMap (3) as HttpContextLifecyle. Stepping through the code, executing DisposeAndClearAll() does not call the Dispose method on EfUnitOfWork. Thanks for any help you could offer.

      protected void Application_EndRequest(Object sender, EventArgs e)
        {
            // Will call dispose on IDisposable objects in IoC container that
            // have been scoped to the request.
            HttpContextLifecycle.DisposeAndClearAll();
        }

For<IUnitOfWork>().LifecycleIs(new HttpContextLifecycle())
                        .Use(new EfUnitOfWork(new DynamicDbContext(AppConfig.Instance[ConfigSettings.PEDB_CONNECTIONSTRING])));

 public class EfUnitOfWork : IUnitOfWork, IDisposable
...
private bool _disposed;        
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _dbContext.Dispose();
                }
            }
            _disposed = true;
Reply all
Reply to author
Forward
0 new messages