如何使用Autofac确保每个请求有一个NHibernate ISession?

Mic*_*out 3 nhibernate asp.net-mvc dependency-injection autofac

我在Application_Start方法中使用的Autofac模块中有以下代码:

builder.Register(c => new Configuration().Configure().BuildSessionFactory())
    .SingletonScoped();
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
    .HttpRequestScoped();

builder.Register<NHibernateSomethingRepository>().As<ISomethingRepository>();
Run Code Online (Sandbox Code Playgroud)

存储库的构造函数将ISession作为参数.但是我最终为整个应用程序提供了一个会话,即使我明确要求它是HttpRequestScoped.

我已经配置了ContainerDisposal HTTP模块.

根据文档,您必须创建一个嵌套容器,但我让Autofac自动装配依赖项.

我该怎么办?

谢谢!

Mic*_*out 8

我发现了问题,所以我会回答我自己的问题.

我使用默认范围注册了我的存储库,在Autofac中是单例范围.我应该这样做:

builder.Register<NHibernateSomethingRepository>()
    .As<ISomethingRepository>()
    .HttpRequestScoped;
Run Code Online (Sandbox Code Playgroud)