I'm using bltoolkit in my ASP.Net application , I use repository pattern to manage my data access layer. foreach operation i open a new DbManager . I cannot find a way to open and dispose the DbManager Object per request or session . any ideas
Asked
Active
Viewed 602 times
1 Answers
0
IMHO, best way of usage:
public IEnumerable<int> GetMyTableIds()
{
using (var dbManager = new DbManager("database"))
{
return dbManager.GetTable<MyTable>()
.Select(table => table.Id)
.ToArray();
}
}
Call of
new DbManager("database")
can be extracted to factory.
Or you may use thread static variables
static class DbManagerContainer
{
[ThreadStatic]
public static DbManager DbManager;
}
public void Request_Start()
{
DbManagerContainer.DbManager = new DbManager("database");
}
public void Request_End()
{
if (DbManagerContainer.DbManager == null)
{
//Write warn to log. This is not normal case.
}
else
{
DbManagerContainer.DbManager.Dispose();
DbManagerContainer.DbManager = null;
}
}

neodim
- 468
- 4
- 15
-
what i need exactly to open one DB manager per request which was made using HTTPContext items and on Request_Start event open a new DBManager then dispose it in Request_Event – user2971927 Feb 09 '14 at 05:43
-
Why do you need split open and dispose DBManager to different methods? Use DbManager in local context only. – neodim Feb 10 '14 at 04:31
-
Because I need one DBManager per request, my site get thousands of hits and each request make many trips to the DB so it is difficult to open a new DBManager with each operation. Another thing is that I use lazy loading with a one generic repository method which return generic queryable object so I need an open session, because if I'm using "using" keyword it will dispose the DBManager once i got out of the using scope so when i call queryable.ToList method it will find a disposed DB Manager – user2971927 Feb 10 '14 at 06:17
-
that is an alternative solution for this case but still my solution is recommended. using HTTPContext over ThreadStatic, you can see this article http://www.hanselman.com/blog/ATaleOfTwoTechniquesTheThreadStaticAttributeAndSystemWebHttpContextCurrentItems.aspx – user2971927 Feb 11 '14 at 06:29