I am using CommonSrviceLocator with WindworContainer for resolving my NHibernage.ISession instances. ISession instances is created through SessionFactory. For some reason I need to work with different databases in one application, so I need different connection strings and different NHibernate.ISession objects.
SessionFactory can create different ISession objects by DB name. So I want to get different ISession objects in my application using following syntax:
ISesssion sessionForDb1 = ServiceLocator.Current.GetInstance<ISession>("session-for-db1");
ISesssion sessionForDb2 = ServiceLocator.Current.GetInstance<ISession>("session-for-db2");
To achieve that I've created following container registrations:
IWindsorContainer container = new WindsorContainer();
container.AddFacility<FactorySupportFacility>();
container.Register(
Component.For<ISessionFactory>()
.Named("session-factory-for-db1")
.LifeStyle.Singleton
.UsingFactoryMethod(() => new NHibernateConfigurator().CreateSessionFactoryForDb1()),
Component.For<ISessionFactory>()
.Named("session-factory2-for-db2")
.LifeStyle.Singleton
.UsingFactoryMethod(() => new NHibernateConfigurator().CreateSessionFactoryForDb2()),
Component.For<ISession>()
.Named("session-for-db1")
.LifeStyle.PerWebRequest
.UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>("session-factory-for-db1").OpenSession()),
Component.For<ISession>()
.Named("session-for-db2")
.LifeStyle.PerWebRequest
.UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>("session-factory2-for-db2").OpenSession())
);
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
This works, but the thing I don't like here is that I need to create a lot of string constants that represents families of objects and build each with the other naming each instance. So for this task I need to register 4 string constants, if my SessionFactory must be created with another factory I will probably need to define 6 constants, etc.
I would like to know if there is any better approach for registering similar families of objects?