I have a problem managing the lifetime of open database connections with StructureMap scoped to HttpContext
when there are persistent HTTP connections in my ASP.NET MVC application, like SignalR hubs.
My DI container, StructureMap, injects an open IDbConnection
into several services. To ensure that these database connections are closed and properly disposed of, I call ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects()
on the EndRequest
event.
This works great for MVC controllers until a service requiring a database connection is injected into a SignalR hub, which keeps a persistent HTTP connection open for each client and eventually saturates the connection pool.
If I scope IDbConnection
to a singleton, only one connection is ever opened per-application and the pool doesn't saturate, but this is a bad idea in case the connection is ever locked or times out.
So maybe there is a way to customise the scope of database connections for my SignalR hubs? I tried resolving a service instance in each Hub method, but this still instantiates a database connection at the HttpContext scope and keeps it open for the duration of the calling client's hub connection.
How should I manage the lifetime of database connections with StructureMap in an HTTP-scoped context when there are persistent HTTP connections around?
public class MyService
{
private IDbConnection _con;
public MyService(IDbConnection con)
{
_con = con;
}
public IEnumerable<string> GetStuff()
{
return _con.Select<string>("SELECT someString FROM SomeTable").ToList();
}
}
public class MyHub : Hub
{
private MyService _service;
public MyHub(MyService service)
{
_service = service; // Oh Noes! This will open a database connection
// for each Client because of HttpContext scope
}
public Task AddMessage()
{
var result = _service.GetStuff();
// ...
}
}
For<IDbConnection>()
.HybridHttpOrThreadLocalScoped()
.Use(() => BaseController.GetOpenConnection(MyConnectionString));
public class GlobalApplication : System.Web.HttpApplication
{
public GlobalApplication()
{
EndRequest += delegate
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
};
}
// ...
}
In SignalR 1.0.0 Alpha, Hub
's implement IDisposable
. SignalR Hub
instances are ephemeral unlike the HttpContext
, so if you close your your IDbConnection
in the Hub
's Dispose
method, you shouldn't unnecessarily saturate your connection pool.
First, configure a named, transient database connection instance in StructureMap:
For<IDbConnection>()
.Transient() // scope
.Add(x => BaseController.GetOpenConnection(connectionString, IsDebugging()))
.Named("Transient");
Make sure you configure this before your default instance, or it will override the default instance.
Secondly, inject an IContainer
into your SignalR hub so you can build a nested StructureMap container:
public class JobHub : Hub
{
private readonly IContainer _container;
public JobHub(IContainer container)
{
_container = container;
}
public Task DoStuff(string input)
{
// ...
Instantiate a nested container in your SignalR method and resolve your named transient database connection:
using (var httpRequestScope = _container.GetNestedContainer())
{
var transientConnection =
httpRequestScope.GetInstance<IDbConnection>("Transient");
Use .With<IDbConnection>(transientConnection)
to ensure services and repositories instantiated by your nested container use this connection:
var myService = httpRequestScope
.With<IDbConnection>(transientConnection)
.GetInstance<MyService>();
var result = myService.DoStuff(input);
return Clients.addResult(result);
}
}
}
Finally, the scoped using (...)
statement will ensure that your nested container cleans up after itself, including the database connection.
The downside here is that you are opening and closing a database connection for every SignalR method call, but since connections are pooled, releasing early may not be so bad. Your mileage should depend on your SignalR request volume.
You may be able to ditch the nested container and just ask DependencyResolver.Current
for the named connection instance, but then you may have to remember to explicitly close each connection to prevent a leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With