使用依赖关系注入尝试使用 ASP.NET 5/EF7 进行 n 层的几个问题



我目前的设置是这样的:演示文稿(ASP.NET MVC)->服务(Web API)->业务逻辑->DAL。我正在尝试依赖注入,所以我对如何实现它还不太熟悉。

现在,我在设置中传递依赖项时遇到问题。这是代码:

在 BLL 中:

public class StudentLogic : IStudentLogic
{
    private IStudentRepository _studentRepository;
    public StudentLogic(IStudentRepository repo)
    {
        _studentRepository = repo;
    }
    //  Some codes ommitted
}

在 DAL 中:

public class StudentRepository : IStudentRepository
{
    private TestDbContext _context;
    public StudentRepository(TestDbContext context)
    {
        _context = context;
    }
}

所以我在 BL 层有这个,它由服务层中的 Web API 调用。问题是由于构造函数采用IStudentRepository,我被迫在服务层中引用DAL,因为我需要在服务层中调用的StudentLogic构造函数中传递I IStudentRepository。我想我做错了,所以我的问题是:

  1. 如何在不引用服务层中的 DAL 的情况下解析依赖关系?我想我需要使用 IoC 容器,但我不确定如何使用。

  2. 如果问题 1 得到解决,则意味着我可以使用传递的 IStudentRepository 调用 StudentLogic。StudentRepository需要在其构造函数中传递一个DbContext,以便我可以执行事务。我也该如何解决此上下文。

一个例子将非常有帮助。我了解 DI,但到目前为止,我只使用手动注入,所以我不确定如何使用 IoC 来做到这一点。

不幸的是,

某个地方的某个人必须知道如何连接这些点。理想情况下,这只会发生在应用程序的入口点(WebApi 或集成测试)。

仍然可以实现良好的数据持久性抽象级别。

尝试采取Onion Architecture方法。

http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

简而言之,您的应用程序堆栈将类似于:

     WebApi           Integration
      (UI)               Tests
       |___________________|
                |
       _________|__________
       |                   |
  Application       Infrastructure
 Service Layer      Service Layer
     (BLL)              (DAL)
       |__________________|         
                | 
                |
          Domain Model
              Layer 

您的IStudentRepository以及(我假设)您的Student对象将被安置在Domain Model Layer中。

Infrastructure Layer中实施您的IStudentRepository

最后是StudentLogic Application Service Layer的服务。

这使您能够实现特定于所选数据访问方法的许多Infrastructure项目。但是,在这种情况下EntityFramework您可能希望拥有一个Azure Blob Storage数据持久性项目或将外部 api 包装器抽象到其自己的基础结构项目中。

每个基础设施项目都可以存在于自己的项目中

这会将数据持久性知识与应用程序的"核心"分离。

(WebApi -> Application Services -> Domain Model) 

最新更新