ASP DBContext Best Practies
本文关键字:Practies Best DBContext ASP | 更新日期: 2023-09-27 18:32:34
在谷歌搜索了一段时间后,我想知道DBContext(EntityFramework或Linq-to-Sql)的最佳实践方法。
在实践中,我会撒谎知道以下"模式"中的哪一种缺点较少:
1) 从这里获取代码
public class ContextFactory
{
[ThreadStatic]
private static DBDataContext context;
//Get connectionString from web.config
private static readonly string connString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
public static DBDataContext Context()
{
if (context == null)
context = new DBDataContext(connString);
return context;
}
public static void FlushContext()
{
context = new DBSkillDataContext(connString);
}
}
这样,每次初始化控制器时,我都会使用 FlushContext。
2)以这种方式(从这里获取代码)
public class UnitOfWork : IUnitOfWork, IDisposable
{
DBContext context= null;
IUserRepository userRepo = null;
IAccountRepository accountRepo = null;
public UnitOfWork()
{
context= new DBContext();
userRepo= new UserRepository(context);
accountRepo= new accountRepo(context);
}
public IUserRepository userRepo
{
get
{
return userRepo;
}
}
public IAccountRepository accountRepo
{
get
{
return accountRepo;
}
}
public void Dispose()
{
// If this function is being called the user wants to release the
// resources. lets call the Dispose which will do this for us.
Dispose(true);
// Now since we have done the cleanup already there is nothing left
// for the Finalizer to do. So lets tell the GC not to call it later.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing == true)
{
//someone want the deterministic release of all resources
//Let us release all the managed resources
context= null;
}
}
~UnitOfWork()
{
// The object went out of scope and finalized is called
// Lets call dispose in to release unmanaged resources
// the managed resources will anyways be released when GC
// runs the next time.
Dispose(false);
}
}
public abstract class AController : Controller
{
private IUnitOfWork IUnitOfWork;
protected IUnitOfWork UnitOfWork_
{
get { return IUnitOfWork; }
}
public AController(IUnitOfWork uow)
{
this.IUnitOfWork = uow;
}
}
public class UserController : AController
{
// use our DbContext unit of work in case the page runs
public UserController()
: this(new UnitOfWork())
{
}
// We will directly call this from the test projects
public UserController(UnitOfWork unitOfWork)
: base (unitOfWork)
{
}
public ActionResult Index()
{
List<User> users= UnitOfWork_.usersRepo.GetUsers();
return View(users);
}
}
所以我要问的是,以上哪一个是最佳实践?
不要使 DbContext 成为静态的。DbContext 不是线程安全的,将其设置为静态使其易于从多个线程使用 - 尤其是在可能导致难以调试/解决错误甚至数据损坏的情况下。此外,长时间保持上下文活动不是一个好主意 - 它将跟踪越来越多的实体,因此会逐渐变得越来越慢。它还将阻止 GC 收集正在跟踪但未使用的对象。另一个例子要好得多。DbContext本身就是一种UnitOfWork。我不确定我是否会从这里的存储库模式开始。我宁愿直接使用 DbContext,并在模式从我的代码中出现时才使用模式,并且只有在使用该模式有好处的情况下才使用它们(请注意,模式需要更多需要理解和维护的代码)。