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 (i.e. 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 ausingscope. If you want to be more 'IoC gotcha' independent, you can have for example aIConnectionFactorylike this: