what is the preferred practice when linq2sql using (in asp.net mvc applications): to create "singleton" for DataContext
like:
partial class db
{
static db _db = new db(global::data.Properties.Settings.Default.nanocrmConnectionString, new AttributeMappingSource());
public static db GetInstance()
{
return _db;
}
}
or to retrieve new instance when it needed within using
:
using (db _db = new db())
{
...
}
the usage of using
brings some limitations into code. so I prefer to use singleton one. is it weird practice?
UPD:
explanation why i'm using singleton:
public class UserGroupRepository
{
public static IQueryable<Group> RolesFor(string username)
{
User user = UserRepository.WithUsername(username);
return from g in db.GetInstance().Groups
join ug in db.GetInstance().UsersGroups on g.Id equals ug.GroupId
where ug.UserId == user.Id
select g;
}
}
i have this method. due to it returns IQueryable - I can continue composing query without it executing, so here just lazy result returns.
if i rewrite the same code with using
- i cannot be able to return IQueryable (because db will be disposed and IQueryable will be lost too), and i would change it to List. and now this method will return "huge" List from which i will filter data on previous function.
i hope i describe enough detailed.