Supporting multiple databases with NHibernate - take 1

by Mikael Henriksson 18. March 2010 04:27

This is a very naive and silly attempt but it’s working. I suppose under high work load and supporting many databases I guess you need to shield the web servers from having to host too many SessionFactories.

This was the simplest way I could think of. I am actually getting the connection string as a shard key and use that both for connecting to the database and as a lookup key. Instead of creating a SessionFactory at application startup I just build the configuration WITHOUT connection string and set spin up a new SessionFactory first time it is requested. It needs to be a singleton so I don’t know how to time out the darn thing if it’s not needed for a long time but I can worry about that later. First make it work, then make it work good right?

public class ShardService : IShardService
{
	public ISessionFactory GetSessionFactory(string shardKey)
	{
		var factory = ObjectFactory.TryGetInstance<ISessionFactory>(shardKey);

		if (factory == null)
			return CreateSessionFactory(shardKey);

		return factory;
	}

	public ISessionFactory CreateSessionFactory(string shardKey)
	{
		var config = ObjectFactory.GetInstance<Configuration>();
		config.SetProperty(global::NHibernate.Cfg.Environment.ConnectionString, shardKey);

		ISessionFactory factory = config.BuildSessionFactory();
		ObjectFactory.Configure(x => x.ForSingletonOf<ISessionFactory>().Use(factory).Named(shardKey));
		return factory;
	}
}

Tags: ,

NHibernate | C#

About the author

Life architect specialized in programming