"Binding" objects to the top level Page class

D

Davíð Þórisson

asking a lot these days... how would I ever learn .Net without the
newsgroups!! Well I'm stuck on yet another point. All pages on my web have a
user control (initialise) that handles for example database connection;
opens db on page_onload and closes db on page_unload. But so that the
connection object is as easily accessible from all subpages and other user
controls I'd like to somehow "bind" it to the top level Page class.
Otherwise I foresee problems with accessing the db object from sub-codes.
Can anyone please tell me how do to this kind of thing?? Or should I maybe
use some other way?
 
K

Karl Seguin

I think most people would tell you two answers:

First, the typical way to achieve what you are trying to do is to use a
comon base-page for all of your pages:

public class MyBasePage
inherits System.Web.UI.Page

private _connection as SqlConnection
public property Connection as SqlConnection
get
return _connection
end get
set
_connection = value
end set
end property


sub page_load
_connection = new Sql...
end sub



and have all your pages inherit from it:

public class WebForm1
Inherits MyBasePage



But the other thing people would tell you is that you shouldn't be using
connections like this. There are a couple good reasons. First of all,
codebehind is a presentation logic layer, and it shouldn't do anything with
System.Data.SqlClient (some people, like me would say it shouldn't do
anything with the complete System.Data namespace, but that's for another
day). You should be using a data access layer through a business layer for
all database connection stuff. Secondly, even if you ignore the first piece
of advice, you shouldn't be opening a single connection and closing it at
the end of the request. You should open connections as late as you need
them and close them as soon as you are done with them. Thanks to connection
pooling it's much better to open and close connections 20 times in a page's
life, than to hold one open at the start and close it at the end...

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top