开发者

Static DB Provider in ASP.NET MVC Causing Memory Leak

开发者 https://www.devze.com 2023-01-02 23:38 出处:网络
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:-

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()
    {
        IDatabaseT开发者_运维知识库ableObject 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?


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


Apparently this will cause a memory leak.

0

精彩评论

暂无评论...
验证码 换一张
取 消