【发布时间】:2011-09-11 15:18:01
【问题描述】:
与大多数人一样,我已经开始了解实体框架的某些细节。其中之一是上下文的生命周期。我正在使用存储库并已决定上下文将在请求的长度内存在。因此,无论在何处使用该存储库,都需要从 Web 层注入上下文。
我已经编写了一些我确信可以重构的代码(事实上,绝对可以!)。那么基于上面的概念,你会如何优化下面的仓库助手呢?
public class RepositoryHelper
{
public static CountryRepository GetCountryRepository() {
return new CountryRepository(HttpContext.Current.GetObjectContext());
}
public static CurrencyRepository GetCurrencyRepository()
{
return new CurrencyRepository(HttpContext.Current.GetObjectContext());
}
public static SettingRepository GetSettingRepository()
{
return new SettingRepository(HttpContext.Current.GetObjectContext());
}
}
存储库非常简单,看起来像
public class CountryRepository
{
private Context _context = null;
public CountryRepository(Context context)
{
_context = context;
}
public Country GetById(int id)
{
// Would return a country
}
public IEnumerable<Country> All()
{
// Would return a list of countries
}
}
【问题讨论】:
标签: c# .net entity-framework interface dependency-injection