One website with multiple connection strings using asp mvc 2 and nhibernate

On my website, I am using ASP MVC 2 + Fluent NHibernate as orm, StructureMap for the IoC container.

There are several databases with the same metadata (and therefore entities and mappings are the same). On the LogOn page, the user fixes the login, password, remembers and selects his server from the drop-down list (in fact, he selects the database).

Web.config contains all connstrings, and we can assume that they will not be changed at runtime.

I assume that for each database one factory session is required.

Before using multiple databases, I loaded the classes into my StructureMap ObjectFactory in Application_Start

ObjectFactory.Initialize(init => init.AddRegistry<ObjectRegistry>()); ObjectFactory.Configure(conf => conf.AddRegistry<NhibernateRegistry>()); 

NhibernateRegistry Class:

 public class NhibernateRegistry : Registry { public NhibernateRegistry() { var sessionFactory = NhibernateConfiguration.Configuration.BuildSessionFactory(); For<Configuration>().Singleton().Use( NhibernateConfiguration.Configuration); For<ISessionFactory>().Singleton().Use(sessionFactory); For<ISession>().HybridHttpOrThreadLocalScoped().Use( ctx => ctx.GetInstance<ISessionFactory>().GetCurrentSession()); } } 

In Application_BeginRequest, I associate an open nhibernate session with an asp session (nhibernate session for each request), and in EndRequest I unlink them:

  protected void Application_BeginRequest( object sender, EventArgs e) { CurrentSessionContext.Bind(ObjectFactory.GetInstance<ISessionFactory>().OpenSession()); } 

Q1: How can I understand that I should use SessionFactory according to the authenticated user? this is something like UserData populated with the database name (I use Simple FormsAuthentication)

For logging, I use log4net, namely AdoNetAppender, which contains connectionString (in xml, of course). Q2: How can I manage multiple connection strings for this database application, so the logs will be written to the current database? I have no idea how to do this, except changing the xml all the time and reselling the xml configuration, but this is a really bad solution.

+4
source share
1 answer

I assume that for each database one factory session is required.

Not; You can do a great job with one factory session for both databases.

You simply pass an open IDbConnection as a parameter to the OpenSession() ISessionFactory .

Thus, you will lose the opportunity for a second level cache, but this may not be a problem.

If you need a second level cache, you need to implement your own DriverConnectionProvider and provide it using the free nh Provider<TYourDriverConnectionProvider>() method.

+1
source

Source: https://habr.com/ru/post/1312171/


All Articles