I had a problem managing the lifetime of open database connections with StructureMap with the HttpContext when my ASP.NET MVC application has persistent HTTP connections such as SignalR hubs.
My DI container, StructureMap, introduces an open IDbConnection into several services. To ensure that these database connections are closed and correctly removed, I call ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects() in the EndRequest event.
This is great for MVCs until a service that requires a database connection is injected into a SignalR hub, which maintains a constant HTTP connection for each client and ultimately saturates the connection pool.
If I use IDbConnection for singleton mode, only one connection is open for each application and the pool is not saturated, but this is a bad idea . in case the connection is blocked or disconnected.
So maybe there is a way to configure the database connection area for my SignalR hubs? I tried to resolve the service instance in each Hub method, but this still creates a database connection in the HttpContext area and keeps it open for the duration of the client hub connection.
How can I control the lifetime of database connections with StructureMap in the context of HTTP hosts when there are persistent HTTP connections?
Code example
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;
StructureMap Configuration
For<IDbConnection>() .HybridHttpOrThreadLocalScoped() .Use(() => BaseController.GetOpenConnection(MyConnectionString));
Global.asax.cs
public class GlobalApplication : System.Web.HttpApplication { public GlobalApplication() { EndRequest += delegate { ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects(); }; }
asp.net-mvc structuremap lifetime signalr
Petrus theron
source share