views:

338

answers:

1

Question follows on from http://stackoverflow.com/questions/2655861/fluent-nhibernate-multiple-databases (no need to follow this link,there should be enough background here).

My problem is this:

I'm using Fluent NHibernate. My application uses multiple databases. Each database has its own entities registered (mapped) against it. The result is that have multiple Session Factories, each one relating to a single DB, and each 'containing' its own set of mapped entities.

For loading entities I've created a generic Factory class that provides some standard load methods usable for any registered entity (in any DB). The problem is: The load methods need to use the correct session factory for the entity class I'm busy dealing with. How would I determine which session factory I need to use? I have all the Session Factories 'on hand' (and indexed by database name), I just need a way, knowing just the type of Entity I'm about to load, of choosing the right Session Factory to use.

For example:

public IBaseBusinessObject CreatePopulatedInstance(Type boType, Guid instanceKey)
{
  IBaseBusinessObject result = null;
  ISessionFactory sessionFactory = GetSessionFactory(boType);
  using (ISession session = sessionFactory.OpenSession())
  {
    using (session.BeginTransaction())
    {
      result = (IBaseBusinessObject)session.Get(boType, instanceKey);
    }
  }
  return result;
}

What needs to go on in GetSessionFactory(boType) ?

Thanks for reading!

+1  A: 

I'd start with looking at the ISessionFactory.GetClassMetaData method.

IClassMetadata metadata = sessionfactory.GetClassMetadata(boType); 

If you can maintain a list of your ISessionFactory instances, you can enumerate your way through them until you find the one which has metadata for your type boType.

I've never used it and don't have my references to hand, but I'd expect it to either return null or raise an exception if it doesn't recognise the type. If you get a value for metadata without an error, then that's your session factory.

Good luck

Neil.

Neil Moss
Great thanks. This solution worked.
Trevor
The GetClassMetadata() method returns null if the specified type is not managed by the Session Factory in question.
Trevor
You're welcome.
Neil Moss