We have a ServiceStack service (API) which provides HTTP endpoints hosted using AppSelfHostBase. Those services later query database using ServiceStack.OrmLite.MySql. All methods are implemented using async / await pattern. Database connections are registered manually to Funq with Request reuse scope, and injected to the property of base DAL class.
This all works fine when this service is accessed only by HTTP requests. We have another Windows service which calls this API. Since they could be hosted on the same server, we’ve implemented local IRestClientAsync for wrapping service calls, so the API service methods could be loaded to the Windows service, and accessed more efficiently (eg 1200 req/sec compared to 400 req/sec). This Windows service has a lot of threads running at the same time. By doing this, we broke the Request lifecycle and are getting
“There is already an open DataReader associated with this Connection which must be closed first.”
error. We tried handling this manually using custom connection providers separating connections through threads using ThreadLocal and CallContext. This didn’t work all the time.
We tried handling Request lifecycle by calling OnBeginRequest(null);
and OnEndRequest();
manually, but the performance was bad (close to HTTP calls) and also, got “open DataReader” errors.
We are using RequestContext.UseThreadStatic
option, since the threads are instantiated from Quartz .NET job.
What could be the best solution for managing database connections? Can we make the current solution working reliably?