コントローラ内のDispose()
メソッドは、必ずしも信頼できるとは限りません。同様に、セッションもおそらく良いアイデアではありません。 「Best」はおそらく主観的ですが、Dependency Injection(Castle Windsor)を使用し、Unit Unit of Work Repositoryのパターンに従うことで最も成功しました。
セットアップ次の行に沿って作業単位:
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のものではなく、リポジトリではなく、より基本的なものに焦点を当てています。私は、リポジトリとDIコンテナを使用せずにbegin/endrequestイベントまたはコントローラクラスの両方でどのアプローチが最善であるか疑問に思っています。 – Ray
開始/終了要求イベントにアタッチすることで、コントローラの中だけでなく(フィルタなど)、要求の全期間を通じてデータインターフェイスの同じインスタンスにアクセスできますが、最終的には同じです。私が長い説明をする唯一の理由は、ウェブファーム/ウェブガーデンのリクエストコンテキストで問題を追跡することに問題があったためです。これが最終的にはうまくいきました。 – lukiffer
遅延ロードをサポートするには両方の方法が理にかなっていますか? – Ray