请在以下情况下纠正我。(问题在最后)
(我问了一个类似的问题,没有组织,投票结束。所以我把这里的问题总结成一个可以用准确答案回答的范围。)
我正在使用 nhibernate 作为 ORM 开发具有多个层的 Web 应用程序。我的层结构如下
- 模型层
 - 存储层
 - 服务层
 - 界面层
 
有了上面的层,类和接口放置如下。
ProductController.cs(用户界面层)
public class ProductController : Controller
{
    ProductServices _ProductServices;
    NHibernate.ISession _Session;
    public ProductController()
    {
        _Session = SessionManager.GetCurrentSession();
        _ProductServices = new ProductServices(
            new ProductRepository(), _Session);
    }
    // Cont..
 }
ProductServices.cs(服务层)
public class ProductServices : IProductServices
{
    protected IProductRepository _ProductRepository;
    protected NHibernate.ISession _Session;
    public ProductServices(IProductRepository productRepository,
        NHibernate.ISession session)
    {
        _ProductRepository = productRepository;
        _Session = session;
        _ProductRepository.SetSession(_Session);
    }
    // cont...
}
ProductRepository.cs(存储库层)
public class ProductRepository : IProductRepository
{
    NHibernate.ISession _Session;
    public void SetSession(NHibernate.ISession session)
    {
        _Session = session;
    }
    public IEnumerable<Product> FindAll()
    {
        return _Session.CreateCriteria<Product>().List<Product>();
    }
    //cont..
}
在 UI 层,我将会话创建为每个会话的请求,并在类构造函数的帮助下注入服务层。然后借助方法设置存储库的会话。
恐怕如果我将 _Session 作为构造函数直接传递给存储库,我将无法在服务层下控制它。还有一个使用web服务层的未来扩展计划。
** 有没有办法确保在_Session已经设置的 ProductRepository 类的每个方法中,无需在每个方法中编写代码if(_Session==null),因为它重复相同的代码。
**如果上述模式是错误的,请告诉我实现这一目标的正确方法。