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?
Example Code
Typical Service
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();
}
}
Typical SignalR Hub
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();
// ...
}
}
StructureMap Configuration
For<IDbConnection>()
.HybridHttpOrThreadLocalScoped()
.Use(() => BaseController.GetOpenConnection(MyConnectionString));
Global.asax.cs
public class GlobalApplication : System.Web.HttpApplication
{
public GlobalApplication()
{
EndRequest += delegate
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
};
}
// ...
}
GetNestedContainer()
to explicitly dispose of services and open connections it uses. – MaddeningIDbConnection
cannot be transient because of LINQ query materialization in the service layer. – Maddening