控制器中的Dispose()
方法並不總是可靠的。同樣,Session也可能不是一個好主意。 「最佳」可能是主觀的,但通過使用依賴注入(Castle Windsor)和遵循工作單元庫模式,我們取得了最好的成功。
安裝工作的單位大致如下:
public class UnitOfWork : IUnitOfWork
{
public UnitOfWork()
{
this.Context = new MyEFEntities();
this.Context.ContextOptions.LazyLoadingEnabled = true;
}
public void Dispose()
{
this.Context.Dispose();
}
public ObjectContext Context { get; internal set; }
}
設置你的資料庫:在Global.asax中與城堡
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : class
{
public Repository(IUnitOfWork unitOfWork)
{
Context = unitOfWork.Context;
ObjectSet = Context.CreateObjectSet<TEntity>();
}
public ObjectContext Context { get; set; }
public IObjectSet<TEntity> ObjectSet { get; set; }
}
註冊:
void Application_Start()
{
this.Container.Register(
Component.For<IUnitOfWork>()
.UsingFactoryMethod(() => new UnitOfWork())
.LifeStyle
.Is(LifestyleType.PerWebRequest)
);
ControllerBuilder.Current.SetControllerFactory(
new WindsorControllerFactory(this.Container));
}
和使用您的控制器(或您使用它的任何地方,只要它是可注射的):
public class SomeController
{
public SomeController(IRepository<MyEntity> repository)
{
this.Repository = repository;
}
public IRepository<MyEntity> Repository { get; set; }
public ActionResult MyAction()
{
ViewData.Model = this.Repository.ObjectSet.Single(x => x.Condition); //or something...
}
}
感謝您的回覆lukiffer,但我的問題集中在更基礎的東西不存儲庫,而不是DI的東西。我只是想知道什麼方法在begin/endrequest事件或控制器類中最好,而不使用存儲庫和DI容器。 – Ray 2012-03-19 05:40:07
通過附加到開始/結束請求事件,您可以在請求的整個生命週期中訪問相同的datacontext實例,而不僅僅是在控制器中(例如過濾器等),但最終它們是相同的。我提出長篇解釋的唯一原因是因爲我在網上農場/網絡花園的請求上下文中遇到了問題,最終這是唯一有效的工作。 – lukiffer 2012-03-19 05:46:07
你的意思是這兩種方式都可以支持延遲加載,對吧? – Ray 2012-03-19 15:13:01