SessionFactory - 多个数据库的一个工厂
我们遇到的情况是,我们有多个具有相同架构的数据库,但每个数据库中的数据不同。我们正在创建一个会话工厂来处理这个问题。
问题是我们不知道要连接到哪个数据库,直到运行时我们才能提供连接。但是在启动时要获得工厂构建,我们需要使用该模式连接到数据库。目前,我们通过在已知位置创建架构并使用该架构来实现此目的,但我们希望删除该要求。
我无法找到一种在不指定连接的情况下创建会话工厂的方法。我们不希望能够使用不带参数的 OpenSession 方法,但这没关系。
有什么想法吗? 谢谢 安迪
We have a situation where we have multiple databases with identical schema, but different data in each. We're creating a single session factory to handle this.
The problem is that we don't know which database we'll connect to until runtime, when we can provide that. But on startup to get the factory build, we need to connect to a database with that schema. We currently do this by creating the schema in an known location and using that, but we'd like to remove that requirement.
I haven't been able to find a way to create the session factory without specifying a connection. We don't expect to be able to use the OpenSession method with no parameters, and that's ok.
Any ideas?
Thanks
Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实现您自己的
IConnectionProvider
或将您自己的连接传递给ISessionFactory.OpenSession(IDbConnection)
(但请阅读该方法有关连接跟踪的注释)Either implement your own
IConnectionProvider
or pass your own connection toISessionFactory.OpenSession(IDbConnection)
(but read the method's comments about connection tracking)我们提出的解决方案是创建一个类来为我们管理这个问题。该类可以使用方法调用中的一些信息来执行一些路由逻辑来找出数据库在哪里,然后调用 OpenSession 传递连接字符串。
The solution we came up with was to create a class which manages this for us. The class can use some information in the method call to do some routing logic to figure out where the database is, and then call OpenSession passing the connection string.
您还可以使用 Brady Gaster 提供的出色 NuGet 包来实现此目的。我根据他的 NHQS 包制作了自己的实现,效果非常好。
您可以在这里找到它:
http://www.bradygaster.com/Tags/nhqs
祝你好运!
You could also use the great NuGet package from brady gaster for this. I made my own implementation from his NHQS package and it works very well.
You can find it here:
http://www.bradygaster.com/Tags/nhqs
good luck!
遇到这个问题,我想为未来的读者添加我的解决方案,这基本上是 Mauricio Scheffer 所建议的,它封装了 CS 的“切换”并提供单点管理(我更喜欢这个,而不是必须传递到每个会话调用,而不是‘错过’并出错)。
我在客户端身份验证期间获取 connecitonstring 并在上下文中设置,然后使用以下 IConnectinProvider 实现,在会话打开时为 CS 设置该值:
然后在 NHConfig 期间将其连接:
Came across this and thought Id add my solution for future readers which is basically what Mauricio Scheffer has suggested which encapsulates the 'switching' of CS and provides single point of management (I like this better than having to pass into each session call, less to 'miss' and go wrong).
I obtain the connecitonstring during authentication of the client and set on the context then, using the following IConnectinProvider implementation, set that value for the CS whenever a session is opened:
Then wire it in during NHConfig: