[英]How to manage NHibernate Sessions per request in Structuremap.MVC5
I'm new to IoC and NHibernate, and am having a great deal of difficulty trying to get my head around best practices for dependency injection. 我是IoC和NHibernate的新手,并且在尝试依赖注入的最佳实践方面遇到了很大的困难。 I've spent the last couple of days looking around and reading documentation, but unfortunately the documentation I've found has been either obsolete or incomplete.
我花了最近几天环顾四周并阅读文档,但遗憾的是我发现的文档已经过时或不完整。
For instance, this tells me what to do, I but I have no idea how to do it. 例如,这告诉我该怎么做,我但我不知道该怎么做。 XSockets.Net - how to manage NHibernate Session Context
XSockets.Net - 如何管理NHibernate会话上下文
I have learned that, according to the official documentation , I need to use nested containers in structuremap to make sure that sessions are created and disposed appropriately for each request. 我了解到,根据官方文档 ,我需要在结构图中使用嵌套容器,以确保为每个请求创建和处理会话。 Unfortunately the examples are all set within unit tests that construct their own container.
不幸的是,这些示例都是在构建自己的容器的单元测试中设置的。 I have no idea how to apply this to MVC.
我不知道如何将其应用于MVC。
If I have a repository like this 如果我有这样的存储库
public class Repository : IRepository {
public Repository(ISession session) {
...
}
...
}
How do I make this work: 我该如何工作:
public NHibernateRegistry()
{
ISessionFactory factory = config.BuildSessionFactory();
For<IRepository>.Use<Repository>()
For<ISession>.????????
}
Or have I got it all backwards somehow? 或者我以某种方式倒退了吗?
So, it turns out that this behaviour is automatic - I don't need to switch it on. 因此,事实证明这种行为是自动的 - 我不需要打开它。 I was making an unrelated error and thought that this was the problem.
我做了一个无关的错误,并认为这是问题所在。 It isn't helped by somewhat unclear documentation.
有些不清楚的文档没有帮助。 If you are using the structuremap.MVC5 nuget package then:
如果您正在使用structuremap.MVC5 nuget包,那么:
SessionFactory _factory;
public NHibernateRegistry()
{
_factory = config.BuildSessionFactory();
For<IRepository>.Use<Repository>()
For<ISession>.Use(() => _factory.OpenSession());
}
This will cause structuremap to open a session once per httprequest. 这将导致structuremap每个httprequest打开一次会话。 Of course, you shouldn't open the session here, as there are a bunch of things relating to transactions, binding and unit of work stuff that you'll want to handle properly - but that's a separate NHibernate thing that is beyond the scope of this problem.
当然,你不应该在这里打开会话,因为有很多事情与你想要正确处理的事务,绑定和工作单元相关 - 但这是一个单独的NHibernate事情,超出了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.