开发者

Is it possible to have Ninject Bind the scope conditionally?

Is it possible to resolve conditionally to a correct ISession scope based upon a MVC Action attribute?

Bind<ISession>().ToMethod(ctx => (ISession)NHibernateHelper.Open())
                .InRequestScope();

Bind<ISession>().ToMethod(ctx => (ISession)NHibernateHelper.Open())
                .InSessionScope();

Pseudo code for a possible solution:

Bind<ISession>().ToMethod(...).InSessionScope()
                .WhenActionHasAttribute(LongConversation);

// else use this binding
Bind<ISession>().ToMethod(...).InRequestScope()

Maybe my approach is flawed and I am open for altnerative solutions to my problem.

Depending on the type of web 'conversation' I need to either keep the NHibernateSession around for the HTTP request/response or for the HTTP sessi开发者_JAVA百科on. Most of the conversations only lasts for one HTTP request/response.

Note: InSessionScope as per Fredrik Kalseth


Remo your answer is not correct in every case. There are reason when you should explicetely do ISession access in your controller. i.e. for performance reasons it makes sense to directly query the session in a controller. When a controllers single responsibility is to display for example a certain customer why should you directly call ISession.Load(id)? Everything else might be unnecessary abstraction.


Accessing the session directly from controllers is not a good design anyway. The controller is doing to much in this case.

I'd rather implement different services that get different scoped NHilbernate and inject them into your controllers. This way it should be very easy to define the two required bindings. For example you can add a attribute to the service that declares which session shall be injected and use WhenClassHas in the bindings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜