Reputation: 59336
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?
Upvotes: 1
Views: 139
Reputation: 2439
I had a couple of thoughts about how you can approach working with the MVC framework.
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.
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.
Upvotes: 1
Reputation: 13934
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.
Upvotes: 2