Surya Pratap
Surya Pratap

Reputation: 495

Getting Nhibernate ISession from Controller (Session Per Request) ASP.Net MVC

I have seen many posts of how to setup a session per request in Asp.Net MVC by using ActionFilter or by a DI package to inject the session into the controller. What I wanted to know was, will it be a bad idea/pattern to just make an extension method like :

public static ISession GetNHibernateSession(this Controller controller)
 {
   return SessionFactory.OpenSession();
 }

so that the session can be instantiated when required like :

public ActionResult DoSomething()
    {
      using(  var session = this.GetNHibernateSession())
        {
           // Do something with the session
        }

    }

reasons why this may be a good/bad idea will be greatly appreciated

Upvotes: 1

Views: 610

Answers (1)

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

Good:

  • It's simple
  • It just works

Bad:

  • You are doing session management, even if it's just a three lines, all over your code
  • With an extension method, you can't replace the behavior for testing

In short, for small, RAD and proof-of-concept projects, your idea will work just fine. For more complex development, it's probably better to extract session management from the controllers, at least moving it to a base class.

Upvotes: 1

Related Questions