0

I have an ASP.NET 4 web application (MVC 4 release candidate, NHibernate 3, Fluent-NHibernate) that needs to read data from two different databases (each on a different server) during the same HttpRequest. I have two repositories: IndividualRepository and ProductRepository. The Individual repository is read-only and connects to database A; the products repository is read/write and connects to database B. Both databases have a connection string in web.config.

My strategy before this "multiple database servers" requirement was imposed on me was to wire up an HttpModule with a static SessionFactoryProvider<WebSessionContext>. It had a static method "GetCurrentSession" that returns ISession via sessionFactoryProvider.GetCurrentSession(). Then on BeginRequest I call sessionFactoryProvider.Bind(), and on EndRequest I call sessionFactoryProvider.Unbind().

With the addition of the second database server, my plan was to create a second static SessionFactoryProvider<WebSessionContext> and corresponding GetCurrentSession method.

For testing puropses, I have 2 NUnit tests (1 for each repository), and I have a similar setup with session factory providers, this time using SessionFactoryProvider<ThreadStaticSessionContext>. I suspect that using ThreadStatic as the session context is part of the problem here, but I can't test both repositories. I haven't been able to get my tests working, so I haven't tried the actual web application.

Am I just writing my tests wrong? Should I be using something other than ThreadStaticSessionContext for my integration tests? I've been able to get each of my test methods working in issolation, but only 1 works when both session factory providers are included. Once I get my tests working, will I have a similar problem using two factory providers with the WebSessionContext in my web app?

Any help would be greatly appreciated!

4

1 回答 1

0

要回答您的问题 - 是的,可以在单个 HTTP 请求中使用 NHibernate 连接到多个数据库服务器。

我自己使用它,但是我显然有与您使用的不同的会话管理。我没有在 中绑定会话BeginRequest(),而是使用 IoC 容器并ISessionBuilder通过控制器的构造函数检索 a ,然后通过sessionBuilder.GetSession().

也就是说,我怀疑您的问题的解决方案将类似于我已经连接的那个。ISessionFactory基本上,我保留了它们的字典(由数据库服务器标识符键入),而不是单个。

如果这不能让您找到可行的解决方案,您可能必须提供您的SessionFactoryProvider.

于 2012-07-16T11:20:00.057 回答