如何使用Autofac确保每个请求有一个NHibernate ISession? [英] How do I make sure that there is one NHibernate ISession per request using Autofac?
问题描述
在我的Application_Start方法中使用的Autofac模块中有以下代码:
I have the following code in an Autofac Module that is used in my Application_Start method:
builder.Register(c => new Configuration().Configure().BuildSessionFactory())
.SingletonScoped();
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
.HttpRequestScoped();
builder.Register<NHibernateSomethingRepository>().As<ISomethingRepository>();
存储库的构造函数采用ISession作为参数.但是,即使我明确要求将其设为HttpRequestScoped,我还是为整个应用程序完成了一个会话.
The constructor for the repository takes an ISession as argument. But I end up with one session for the whole application, even though I explicitly asked for it to be HttpRequestScoped.
我已经配置了ContainerDisposal HTTP模块.
I have configured the ContainerDisposal HTTP module.
根据文档,您必须创建一个嵌套容器,但是我让Autofac自动关联依赖项.
According to the documentation you have to create a nested container, but I'm letting Autofac autowire the dependencies.
我该怎么办?
谢谢!
推荐答案
我发现了问题,所以我将回答我自己的问题.
I found the problem, so I will answer my own question.
我使用默认范围(在Autofac中为单例范围)注册了我的存储库.我应该这样做:
I registered my repository with the default scope, which in Autofac is singleton scope. I should have done this:
builder.Register<NHibernateSomethingRepository>()
.As<ISomethingRepository>()
.HttpRequestScoped;
这篇关于如何使用Autofac确保每个请求有一个NHibernate ISession?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!