与大多数人一样,我一直在关注Entity Framework的某些细节。其中一件事是上下文的生命周期。我正在使用一个存储库,并决定一个上下文将在请求的长度内生存。所以上下文需要从网络层注入,无论使用哪个版本库。重构的成熟 - .NET依赖注入
我写了一些我肯定可以重构的代码(其实绝对是!)。因此,基于上述概念,您将如何优化以下存储库帮助程序?
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
}
}
+1,很好的建议 – smartcaveman 2011-06-09 11:59:09
谢谢拉撒路。为了清楚起见,我已经赞赏示例回购(如果我的示例不完整)。我认为存储库模式正在正确地用于数据访问,并与解决方案中的Web域分离。您的第三段是我最感兴趣的内容 - 即我的web层如何与这些存储库进行交互,而无需编写一个为每个存储库类型注入上下文的哑助手。 – Maleks 2011-06-09 12:38:34
@Maleks:我使用DI容器(Castle Windsor)在存储库实例化时实例化上下文(当活动控制器需要时,它本身通过DI容器实例化)。您的存储库应该都基于您的Web应用程序与之交互的聚合根实体,超出此范围的范围才能深入了解。将存储库的具体实现与数据访问层更紧密地耦合是很好的,这实际上是不可避免的,但存储库耦合的应用应该是松散的。 – Lazarus 2011-06-10 10:46:53