views:

505

answers:

2

My application uses NHibernate with a session per request implementation. I have a core library that provides a thread safe singleton for getting access to the current nhibernate session.

That singleton is leveraged from the web application in the BeginRequest and EndRequest events to ensure the opening and closing of the session with each request. Additionally, my DataAccess layer uses the same singleton to perform data access, so that the same nhibernate session is leveraged.

I've now added Ninject into the equation so that I can infer at runtime, the NHibernate contextual information, namely, the connection string. I'd like to change a value in my web config that tells it which database it will hit. The problem is, in order to do this, I need my singleton (mentioned above) to be able to infer one of it's properties, IConnectionStringProvider.

It's wired up correctly, but the singleton will never have instantiated properties, hence, everything breaks.

So, to my question...how can I get Ninject to work with a singleton, or how can I change my implementation to work with Ninject?

+1  A: 

This is a common problem that many people encounter with Singletons. While I can't comment specifically about NHibernate, check out Misko's Article on why the singleton design pattern suffers from the problem you describe. Be sure to read the comments and linked articles to find out what to do about it ( or search "Where Have All the Singletons Gone?" on google ).

If you're interested in this topic, you may also want to google "singleton-i-love-you-but-youre-bringing-me-down"

Hopefully that helps a little.

Andres
A: 

Maybe you could try binding the singleton to a constant like so

Bind<ISession>().ToConstant(SessionSingleton.Instance);

I do this with the Settings.Default singleton of the Settings object (mostly as a patch method until I have time to really play with my settings) and it works very well.

Jeffrey Cameron