I am pretty new to the NInject binding, and here is what NInject describes.
- TransientBehavior-A new instance of the type will be created each time one is requested.
- SingletonBehavior-Only a single instance of the type will be created, and the same instance will be returned for each subsequent request.
- OnePerThreadBehavior-One instance of the type will be created per thread.
- OnePerRequestBehavior-One instance of the type will be created per web request, and will be destroyed when the request ends.
If I want to bind MembershipProvider to SqlMembershipProvider, should I use SingletonBehavior since I only need one sql membership provider?
ASP.Net already provides a static instance of the current membership provider via the static Membership class and its static Provider property. The binding would likely be in your Application_Start method and look something like this:
Again, because the Memberhip.Provider is a static, it’s sort of like a singleton already, so the behavior you try to apply doesn’t really matter as much.
By not specifying any behavior in the above snippet, Ninject will default to a transient behavior. In this sort of a binding, I believe that will amount to calling the lambda that returns Membership.Provider every time it needs to inject a MembershipProvider type.
I suppose there could be an argument for explicitly specifying a singleton behavior as Ninject would likely “cache” the value returned by the lambda the first time it needs to inject a MembershipProvider, in effect saving the overhead of executing the lambda. I’m not 100% sure that’s how Ninject would work in this situation, but it seems reasonable that it would.
All that said, my personal preference would be to use OnePerRequestBehavior, this way I know Ninject will call my lambda once for each request. Not sure it’s necessary, but I like the idea of getting the provider from Membership.Provider once each request since I suppose you can’t make assumptions about how or when Membership.Provider get’s set, though you could probably find out if you dig enough with Reflector.
Good luck. Sorry your question sat out here so long!