0

I'm trying to wire NCommon and NH to multiple databases via the guidance at http://codeinsanity.com (see 'Configuring NCommon for multiple database support') and it works via the fluent approach suggested, below:

    var configuration = NCommon.Configure.Using(adapter).ConfigureState<DefaultStateConfiguration>();

    configuration.ConfigureData<NHConfiguration>(config => config.WithSessionFactory(() => _sessionFactories[0]).WithSessionFactory(() => _sessionFactories[1]));

This works as expected but as you can see the sessionFactories are hardcoded. What I'd really like to do is something like this:

     foreach(ISessionFactory sessionFactory in _sessionFactories)
     {
          configuration.ConfigureData<NHConfiguration>(config => config.WithSessionFactory(() => sessionFactory));
     }

But this throws the following exception:

Component NCommon.Data.NHibernate.NHUnitOfWorkFactory could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.

My hope is there's a proper way to wire-up n-SessionFactories without hardcoding them - but I'm just not seeing a solution. Any advice?

znelson
  • 919
  • 1
  • 10
  • 24

1 Answers1

0

I thought I got this to work by delegating the SessionFactory piece to a method, as below:

    configuration.ConfigureData<NHConfiguration>(config => ConfigureSessionFactories(config));

    private void ConfigureSessionFactories(NHConfiguration configuration)
    {
        foreach (ISessionFactory sessionFactory in _sessionFactories)
        {
            configuration.WithSessionFactory(() => sessionFactory);
        }
    }

However, that only appears to be a solution. Say you have multiple session factories, you can use all of them to query, but only the last-added session factory will hit the database and return results. Queries against the other session factories will never hit the actual database and will return zero entities.

The only way I've been able to get this to work is:

    configuration.ConfigureData<NHConfiguration>(config => config.WithSessionFactory(() => _sessionFactories[0]).WithSessionFactory(() => _sessionFactories[1]));

I'd rather not hard-code that though.. I'd much rather iterate over a loop of n-session factories... does anyone have an idea of how to accomplish this?

znelson
  • 919
  • 1
  • 10
  • 24