简体   繁体   English

Ninject如何在长时间运行的进程中最好地处理Sql连接?

[英]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). 我们具有一个Azure工作人员角色(与Windows服务基本相同),在该角色中,我们将Ninject用于IoC,并将IDbConnection注入到我们的工作人员中。 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 使用ServiceLocator模式并在我们处理的每条消息上请求一个新的连接
  • 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. 我将排除ServiceLocator(anti)模式。 In my opinion using the NInject concept of Provider<ISomething> would fit your needing. 我认为使用Provider<ISomething>的NInject概念将适合您的需求。 Basically the provider is a sort of factrory returning for you a connection you can use, maybe in a using scope. 基本上,提供程序是一种工厂,可以为您返回可以使用的连接,也许在using范围内。 If you want to be more 'IoC gotcha' independent, you can have for example a IConnectionFactory like this: 如果您想更加独立于“ IoC陷阱”,则可以使用例如这样的IConnectionFactory

interface IConnectionFactory{
           IDbConnection Open();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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