views:

99

answers:

2

Hi, I have got an app I'm going to write in ASP.NET MVC and I want to create a DatabaseFactory object something like this:-

public class DatabaseFactory
{
    private string dbConn get { return <gets from config file>; }

    public IDatabaseTableObject GetDatabaseTable()
    {
    IDatabaseTableObject databaseTableObject = new SQLDatabaseObject(dbConn);
    return databaseTableObject;
    }
}

and this works fine, but I obviously have to instantiate the DatabaseFactory in every controller that needs it. If I made this static, so I could, in theory just call DatabaseFactory.GetDatabaseTable() it would cause a memory leak, wouldn't it?

---------edit------- maybe I need to add in a bit more detail. If I had the above code like this:-

public static class DatabaseFactory
{
    private static string dbConn get { return <gets from config file>; }

    public static IDatabaseTableObject GetDatabaseTable()
    {
        IDatabaseTableObject databaseTableObject = new SQLDatabaseObject(dbConn);
        return databaseTableObject;
    }
}

then instead of my controller code saying

DatabaseFactory databaseFactory = new DatabaseFactory();
var tableObject = databaseFactory.GetDatabaseTable();
List<DbRecord> records = tableObject.Table.ToList();

I just said

var tableObject = DatabaseFactory.GetDatabaseTable();
List<DbRecord> records = tableObject.Table.ToList();

wouldn't that result in the DB connection remaining open once the controller's action method had been GCed?

+1  A: 

Since you don't store the object anywhere, this would not leak memory.

SLaks
Does it not? I thought the if I called that from a controller action in its static form, as there was no DatabaseFactory object created and thus assigned for garbage collection, the databaseTableObject returned would never get closed as the static object never get garbage collected?
I don't see you storing the object anywhere. The fact that the object was returned by a static method is _completely_ irrelevant.
SLaks
Hmmm, I thought that if you instantiated a database connection object in a static object, passed it back to a calling method and used it in the calling method, when the calling method was GCed it wouldn't GC the database connection object as it was "still" referenced by the static object. And as the static object's method would be GCed once it has completed - as it was returning the DB conn object that wouldn't GC it. Sure I found an article somewhere that I wanted to check I understood (but it was that, in a nutshell) - I'll see if I can find it again.Thx
Methods are not GC'd; their variables are. The static class isn't referencing your object at all after creating it.
SLaks
A: 

Apparently this will cause a memory leak.