How to identify a particular entity's Session Factory with Fluent NHibernate and Multiple Databases

StackOverflow https://stackoverflow.com/questions/2698503

문제

Question follows on from 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!

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top