Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / ASP.NET / General / February 2008

Tip: Looking for answers? Try searching our database.

Global instance of an object

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Hornet77 - 08 Feb 2008 12:15 GMT
Hi

I need to call a wide variety of methods to query the database in each
of my aspx pages; to achieve this target I wrote a "DbManager" class
with a private static instance and a set of static method to call from
my pages:

public class DbManager
{
    private static DbManager instance = null;

    public static bool MethodA()
    {
            checkInstance();
            return instance.methodA();
    }

    private static void checkInstance()
        {
            if (instance == null)
            {
                    instance = new DbManager();
            }
        }

    private bool methodA()
    {
        //query database
        return true;
    }

}

in my generic aspx page where I need to query the database I simply wrote:

bool result = DbManager.MethodA();

With this structure I was convinced to have a global instance of
DbManager, created once at application start and never disposed; running
the app, however, I've noticed that the instance need to be re-created
every time I try to call its methods (it appears null and in
checkInstance() it is created new)..... why? is not the "static"
attribute enough to have a single instance of my DbManager class? I need
to add it to Application[] and istantiate it in the start event of
Global.asax?

Thanks in advance for your response
Kevin Spencer - 08 Feb 2008 12:26 GMT
Use a public static class. Then you never need to create an instance of it.

Signature

HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP

> Hi
>
[quoted text clipped - 41 lines]
>
> Thanks in advance for your response
Hornet77 - 08 Feb 2008 13:17 GMT
Kevin Spencer ha scritto:
> Use a public static class. Then you never need to create an instance of it.

Hi Kevin

using a public static class I can't create an istance of it, I agree,
but I WANT to create an instance because there are several parameters I
need to request to a remoted object and I don't want to request, for
example, the connection string to my remote object every time I need to
query the database; so if I can create an istance with all the
parameters inside I can avoid to load the remote server with unnecessary
calls.
Probably a solution could be get the parameters once then store them in
Application[] so they'll be available till the application ends; is this
right?

Thank you
Kevin Spencer - 11 Feb 2008 12:11 GMT
You can store such data in a static class, in a static field or property of
the class.

Signature

HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP

> Kevin Spencer ha scritto:
>> Use a public static class. Then you never need to create an instance of
[quoted text clipped - 13 lines]
>
> Thank you
Mark Rae [MVP] - 08 Feb 2008 13:00 GMT
> public class DbManager

public static class DbManager

That would mean that you would not need to instantiate the class (though you
could if you needed to for other requirements) in order to use its static
methods:
http://www.google.co.uk/search?sourceid=navclient&hl=en-GB&ie=UTF-8&rlz=1T4GZEZ_
en-GBGB252GB252&q=%22C%23%22+%22public+static+class%22


public abstract class DbManager

That would mean that you would not be able to instantiate the class, though
it could be inherited
http://www.google.co.uk/search?hl=en&rlz=1T4GZEZ_en-GBGB252GB252&q=%22C%23%22+%2
2public+abstract+class%22&meta
=

public sealed class DbManager

That would mean that the class could not be inherited i.e. it couldn't be
used as a base class...

I tend to use a combination of the above... E.g. suppose you had a User
class which is used to manage users of your application. You might have a
Create() method, an Update() method and a Fetch() method, all of which you
would probably want to create an instance of the class to give you a User
object whose properties would be populated etc...

However, you might also have a Delete() method whose sole purpose is to
delete a user given a unique identifier. At this point, instantiating a User
object won't really be of much use to you because you don't actually need to
know anything about the user per se at that point - all you want to do is to
delete it. Therefore, the Delete() method could be static, and accept a user
identifier as an argument, returning a boolean to indicate whether the
deletion was successful or not.

E.g.

public class User
{
   private int mintUserID;
   public int intUserID { get { return mintUserID; } set { mintUserID =
value; } }

   private string mstrFirstName;
   public string strFirstName { get { return mstrFirstName; } set {
mstrFirstName = value; } }

   private string mstrLastName;
   public string strLastName { get { return mstrLastName; } set {
mstrLastName = value; } }

   public int Create()
   {
       // create the user and return the ID of the newly created user
   }

   public bool Update()
   {
       // create the user and return success or failure
   }

   public bool Fetch()
   {
       // fetch the user details, populate the class properties and return
success or failure
   }

   public static void Delete(int pintUserID)
   {
       // delete the user with the given UserID and return success or
failure
       // no need to instantiate the User class to do this...
   }
}

Signature

Mark Rae
ASP.NET MVP
http://www.markrae.net

grava - 08 Feb 2008 13:32 GMT
> Hi
>
[quoted text clipped - 27 lines]
>
> }

My Suggestion:

Singleton of DbManager

public class DbManager {
   private static DbManager _instance;

   private DbManager() {
       // constructor
   }

   public DbManager Instance {
       get {
           if (_instance == null)
               _instance = new DbManager();
           return _instance;
       }
   }
}

next create a DbManager Factory in your HttpApplication tied with your
Global.asax or in a BasePage implementation from which you have to derive
all of your pages:

public class BasePage : System.Web.UI.Page {
   protected DbManager DbManager {
       get { return DbManager.Instance; }
   }
}

and for your pages, (eg: default.aspx):

public class _default : BasePage {
   protected void Page_Load(object sender, EventArgs e) {
       DbManager dbManager = this.DbManager;
       dbManager.dostuff();
   }
}

HTH

Signature

Gianluca Gravina
http://blogs.ugidotnet.org/thinkingingrava

bruce barker - 08 Feb 2008 17:04 GMT
your code structure is correct (except for not using locks). either you have
code clearing the instance, or you are getting recycles.

-- bruce (sqlwork.com)

> Hi
>
[quoted text clipped - 43 lines]
>
> Thanks in advance for your response

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.