What will be the way to go with classes in ASP.NET?
Question
In my asp.net web app. I have three classes (inside app_code folder) under namespace WPP
which are as follows:
1. wpp_Common
2. wpp_SQL
3. wpp_Admin
All these classes contains different functions which I am using in my application to accomplish different tasks. Such as, wpp_common
contains a function which make my URL's SEO'd, and wpp_SQL
have some functions which I am using to get details from database.
Now, I am using these classes on different web pages web pages and in web controls. To use these classes I am creating instances of all three classes on the page where I am using them.
protected WPP.wpp_Common ObjCommon = new WPP.wpp_Common();
protected WPP.wpp_SQL ObjSQL = new WPP.wpp_SQL();
protected WPP.wpp_Admin ObjAdmin = new WPP.wpp_Admin();
So, I want to know, is this a better and only way to access my classes by making seprate instances at every page, is this method have any performance constraints.
Or is there a better and logical way to access my classes from ASP.net web pages and web controls.
Thanks.
Solution
If these classes don't encapsulate anything mutable, it may be worth making the key methods utilized static. Then, you don't even need an instance of the class. This seems to make sense for your SEO class. The SQL class you may want a shared instance as it may contain a reference to some SQL connection/class, but this could also be a parameter in a static method.
What you're doing seems okay to me, though.
OTHER TIPS
Really the answer boils down to the complexity of the class. If your classes are lightweight and have low initialization overhead, then you are probably OK with instatiating objects every time. (Heck, even the ASP.NET runtime creates a new instance of your page object every time in classic ASP.NET - not sure about MVC).
But if your object has non-trivial initialization time (intensive processing in constructor or upon first method call), then you'll probably want to look at two options:
One) Storing the object in the session - be careful here as your object may behave differently depending on the backend session store (memory, sql, etc).
MyHeavyObj obj = (MyHeaveyObj) Session["cachedObj"];
if (obj == null)
{
obj = new MyHeavyObj();
obj.Init();
Session["cachedObj"] = obj;
}
obj.DoSomething();
Two) Writing your own Windows Service that serves up your objects via remoting and takes care of initiatlization internally. The drawback here is you need to make sure your service scales as your traffic grows.
MyHeavyObj obj = GetHeavyObjViaRemoting();
obj.DoSomething();