views:

199

answers:

1

Hi

In my website i use ASP MVC 2 + Fluent NHibernate as orm, StructureMap for IoC container.

There are several databases with identical metadata(and so entities and mappings are the same). On LogOn page user fiils in login, password, rememberme and chooses his server from dropdownlist (in fact he chooses database).

Web.config contains all connstrings and we can assume that they won't be changed in run-time.

I suppose that it is required to have one session factory per database.

Before using multiple databases, i loaded classes to 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 bind opened nhibernate session to asp session(nhibernate session per request) and in EndRequest i unbind them:

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

Q1: How can i realize what SessionFactory should i use according to authenticated user? is it something like UserData filled with 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 appender, so logs would be written to current database? I have no idea how to do that except changing xml all the time and reseting xml configuration, but its really bad solution.

A: 

I suppose that it is required to have one session factory per database.

No; you can do just fine with one session factory for both databases.

You just supply an opened IDbConnection as a param to the OpenSession() method of ISessionFactory.

By doing so, you'll lose the possibility for a second level cache, but that might not be a problem.

If you want the second level cache, you need to implement you're own DriverConnectionProvider and supply it via fluent nh's Provider<TYourDriverConnectionProvider>() method.

Martin R-L
Your solution sounds very convincing, will try in a few days. Second level cache isn't essential at all.
jjjjj