ASP.NET MVC 中的 nHibernate 会话范围 - 请求还是操作?
ASP.NET MVC 中的会话事务应该是每个请求还是每个操作,如果它们应该是每个操作(我认为它们应该),当通过 IoC 控制会话时,如何将会话范围限定为每个操作(我是使用 StructureMap 作为我的依赖解析器)?我认为,IoC 容器中作用域生命周期的大多数实现都是按 HttpContext 和/或按线程进行最精细的设置,但 mvc 请求可以通过子操作拥有多个操作。我考虑过在控制事务的操作属性中请求会话工厂并从中创建会话,但是如何确保数据存储库使用与它们正在访问的操作相同的会话?
Should session transactions in ASP.NET MVC be per request or per action, and if they should be per action (which I think they should), how do you scope the sessions to be per action when they are controlled via IoC (I'm using StructureMap as my Dependency Resolver)? Most implementations of a scope lifecycle in IoC containers are per HttpContext and/or per thread at their most granular setup I think, but mvc requests can have multiple actions via child actions. I thought about requesting the session factory in my action attribute controlling my transactions and create a session from that, but then how do you ensure that data repositories use the same session as the action they are being accessed by?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为最直接的方法是使用工厂方法和每个请求范围。然后,会话在实际需要时创建,并保持活动状态直至请求结束。
例如,当您具有延迟加载属性时,每个请求仅使用一个会话会使事情变得更容易。
我不知道 StructureMap,但使用 Castle Windsor,我只需要一行
,会话就可以像魅力一样工作。
I think the most straightforward way is to use factory method and per request scope. Then the session is created when actually needed and stays alive to the end of the request.
Using only one session per request makes things easier when you have lazy load properties for example.
I don't know about StructureMap, but with Castle Windsor I only need one line
and sessions work like a charm.
我最终使用了在全局级别添加到 MVC 的属性,这将为每个操作上下文提供一个新会话。我从中获取信息
http://ayende.com/blog/4809 /refactoring-toward-frictionless-odorless-code-what-about-transactions 和 http://slynetblog.blogspot.com/2011/04/lightweight -nhibernate-and-aspnet-mvc.html。
I ended up using a Attribute added to MVC at the global level that would give me a new session per Action context. I derived information from
http://ayende.com/blog/4809/refactoring-toward-frictionless-odorless-code-what-about-transactions and http://slynetblog.blogspot.com/2011/04/lightweight-nhibernate-and-aspnet-mvc.html.