gpt4 book ai didi

c# - BAL 中的依赖注入(inject)而不添加对 DAL 的项目引用

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:58 24 4
gpt4 key购买 nike

这与发布的问题有关 here .我的核心项目有以下内容。

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。该项目依赖于 Entity Framework 。

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

public class CustomerRepository : IRepository<Customer>
{

}

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

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

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

最佳答案

首先:不要使用公开 IQueryable<TEntity> 的通用存储库.

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

您的问题:

Let' say I have a UI application that will call some API from BAL. Where exactly above code for binding IRepository to CustomerRepository should be placed? Is there any way of doing this binding via App.config?

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

As you can see if I put this somewhere in BAL, then I will have to add a reference to DAL project because I am using CustomerRepository which is defined in DAL layer.

不要在 BAL 中创建引用或配置。 UI 项目是根。所以任何配置都应该添加进去。

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

关于c# - BAL 中的依赖注入(inject)而不添加对 DAL 的项目引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com