依赖注入的对象处理

hoa*_*key 4 c# dependency-injection idisposable repository-pattern

我创建了一个我想在页面后面的代码中使用的存储库类.我在代码隐藏页面中使用构造函数注入来实例化存储库.

存储库类:

BritanniaPremierEntities PBEntities = new BritanniaPremierEntities();

public IQueryable<TradeRoutes> GetRoutes()
{
    var routes = PBEntities.TradeRoutes.OrderBy(c => c.ConsignmentDate);        

    return routes;
}

public IQueryable<TradeRoutes> GetExpiredRoutes()
{
    var routes = PBEntities.TradeRoutes.Where(
        c => c.ConsignmentDate <= System.DateTime.Now);

    return routes;
}
Run Code Online (Sandbox Code Playgroud)

代码页面背后

private IRepository repos;

public Admin_TradeRoutesAdmin()
    : this(new Repository()) 
{
}

public Admin_TradeRoutesAdmin(IRepository repos)
{
    this.repos = repos;
}

public IQueryable GetTradeRoutes()
{        
    // call repository method
    return repos.GetRoutes();
}
Run Code Online (Sandbox Code Playgroud)

这是我有点困惑的地方.我应该如何确保存储库正确处理?例如,我无法使用代码隐藏页面中的语句来包装存储库调用,从而在存储库中使用dispose方法.

Mar*_*ann 5

您应该使用Register Resolve Release模式.

具体而言,您应该记住始终释放您所解决的内容.作曲家有责任跟踪是否应该处理依赖关系.这不是微不足道的,因为它取决于不同的因素:

  • 依赖项是否实现了IDisposable?
  • 依赖关系的生命周期是否表明它应该现在或稍后处理?

这是一项如此复杂的任务,您应该使用适当的DI容器来完成工作.

但是,请记住,这最终取决于您的DI Container是否支持退役.例如,Castle Windsor虽然没有,但StructureMap却没有.