简体   繁体   中英

How to best handle Sql connections in long running processes with Ninject?

We have a Azure Worker Role (basically the same as a Windows Service) where we use Ninject for IoC and have IDbConnection injected into our worker(s). Best practice says that you should dispose the connection as soon as you're not using it anymore, but in a worker/service that may or may not make sense. So what would be a good way of handling the database connection in such a scenario?

Our options include (perhaps not limited too):

  • Using ServiceLocator pattern and request a new connection on every message we process
  • Keep the connection around (ie do nothing with it)

I don't like either to be honest and I was hoping that there was some other solution...

I will exclude the ServiceLocator (anti)Pattern. In my opinion using the NInject concept of Provider<ISomething> would fit your needing. Basically the provider is a sort of factrory returning for you a connection you can use, maybe in a using scope. If you want to be more 'IoC gotcha' independent, you can have for example a IConnectionFactory like this:

interface IConnectionFactory{
           IDbConnection Open();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM