Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

How do I make sure that there is one NHibernate ISession per request using 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>();

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.

I have configured the ContainerDisposal HTTP module.

According to the documentation you have to create a nested container, but I'm letting Autofac autowire the dependencies.

What should I do?

Thanks!

Upvotes: 2

Views: 1633

Answers (1)

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

I found the problem, so I will answer my own question.

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;

Upvotes: 8

Related Questions