1

My expected scenario is the following:

My main action is called. It opens some database connections. At this action's view, I call 2 child actions. These actions should reuse the already opened connections. At the controller's Dispose method I would then close these connections.

It doesn't work because the controller is instantiated again for every child-action. That way I have no idea how to store and manage data that is specific to this request.

I thought of using TempData but it persists to the next request.. I'm not sure it's a good practice.

What should I do?

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • In the MVC pattern, the view should not (generally) be looking into databases. The parent action should be invoking the child actions directly (or performing the equivalent task). By the time the view is rendering, all the data lookup should already be complete. – Carl Raymond Oct 24 '11 at 16:54

2 Answers2

2

Have you considered using DI?

You can register connection with IoC container and specify its lifetime as per request. Than inject this connection to your controller.

frennky
  • 12,581
  • 10
  • 47
  • 63
1

I had a couple of thoughts about how you can approach working with the MVC framework.

View Model\Input Model

If a view requires lots of data which is stored in a variety of different places then create a specific View Model to aggregate it. The point of this technique is to ensure that when the controller returns the view there is no need to go back to the database for further lookups.

This can also be applied to the models which are passed in to a controller action. An Input Model will gather up all the details from the UI ready for the controller to update the underlying domain. As with the View Model the Input Model is in a shape that suits the view and it is the controllers job to then relate this to the domain.

Managing connections

The question does not mention why you need to reuse the connection. In general I have found it is best not to keep a connection to a database open. The .Net framework does a good job of managing a connection pool. Run the query and close the connection as soon as possible. If you are using an ORM like NHibernate then you must ensure that the SessionFactory is only created once for the Application. This can be achieved by creating a singleton for it.

Community
  • 1
  • 1
Keith Bloom
  • 2,391
  • 3
  • 18
  • 30