1

这与此处发布的问题有关。我的核心项目有以下 .

public interface IRepository<T> : IDisposable  
{  
    IQueryable<T> All { get; }  
    IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties);  
    TEntity Find(int id);  
    void InsertOrUpdate(T entity);  
    void Delete(int id);  
    void Save();  
}  

public class Customer  
{  
    public int Id { get; set; }  
    public string FirstName { get; set; }  
    public string LastName { get; set; }   
} 

DAL 有 CustomerContext 和 CustomerRepository。该项目依赖于实体框架。

public class CustomerContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

public class CustomerRepository : IRepository<Customer>
{

}

接下来是我的 BAL。这是一个类库项目。我需要对客户存储库执行一些操作,但我想在不直接添加对 DAL 的依赖的情况下执行此操作。我正在尝试使用 ninject 通过 DI 进行操作。我正在 IRepository 和 CustomerRepository 之间设置绑定,如下所示。

var Kernel = new StandardKernel();  
Kernel.Bind<IRepository>().To<CustomerRepository>();  
  1. 假设我有一个 UI 应用程序,它将从 BAL 调用一些 API。上面用于将 IRepository 绑定到 CustomerRepository 的代码到底应该放在哪里?有没有办法通过 App.config 进行这种绑定?

  2. 如您所见,如果我将它放在 BAL 中的某个位置,那么我将不得不添加对 DAL 项目的引用,因为我使用的是在 DAL 层中定义的 CustomerRepository。

4

2 回答 2

4

首先:不要使用暴露IQueryable<TEntity>.

  1. 您在编写单元测试时是否尝试过模拟它们?
  2. 它们就是我们所说的泄漏抽象。

你的问题:

假设我有一个 UI 应用程序,它将从 BAL 调用一些 API。上面用于将 IRepository 绑定到 CustomerRepository 的代码到底应该放在哪里?有没有办法通过 App.config 进行这种绑定?

为什么不能从 UI 项目中向 DAL 添加依赖项?它还将简化安装,因为在您发布项目和/或创建安装包时会自动包含 DAL。

如您所见,如果我将它放在 BAL 中的某个位置,那么我将不得不添加对 DAL 项目的引用,因为我使用的是在 DAL 层中定义的 CustomerRepository。

不要在 BAL 中创建引用或配置。UI 项目是根。因此,应将任何配置添加到其中。

我通常在每个项目中创建一个组合根,然后从我的启动项目中调用每个程序集的根。这意味着启动项目只需要知道我们得到了哪些项目,而不需要知道它们包含什么。

于 2012-09-24T06:43:10.127 回答
3

你永远不会在低层设置你的容器。相反,您在层次结构的某处有一个组合根。对于桌面应用程序,这Main是一个不错的选择。在 Web 应用程序中,它将Global.asaxApplication_Start.

于 2012-09-23T19:04:41.330 回答