Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在业务层使用Simple injector for repository_C#_Asp.net Mvc_Repository_Simple Injector_Business Layer - Fatal编程技术网

C# 如何在业务层使用Simple injector for repository

C# 如何在业务层使用Simple injector for repository,c#,asp.net-mvc,repository,simple-injector,business-layer,C#,Asp.net Mvc,Repository,Simple Injector,Business Layer,我希望在我的MVC层中根本没有存储库 我的DAL项目层中有genericEFRepository、IRepository和PASContext(从DbContext继承而来) 我已经在我的MVC项目下安装了带有快速启动功能的Simple Injector,这使我能够在每个控制器的构造函数中获得我想要的存储库 但在我的解决方案中,我也有BLL项目,我希望MVC层只与BLL层对话,因为这是项目架构,将来我希望在BLL层的类中添加逻辑 另外,我不想在BLL层中创建上下文,但存储库没有接受0个参数的构造

我希望在我的MVC层中根本没有存储库

我的DAL项目层中有generic
EFRepository
IRepository
PASContext
(从DbContext继承而来)

我已经在我的MVC项目下安装了带有快速启动功能的Simple Injector,这使我能够在每个控制器的构造函数中获得我想要的存储库

但在我的解决方案中,我也有BLL项目,我希望MVC层只与BLL层对话,因为这是项目架构,将来我希望在BLL层的类中添加逻辑

另外,我不想在BLL层中创建上下文,但存储库没有接受0个参数的构造函数,这是我的
ProductBLL
类:

public class BLLProducts
{
    IRepository<Product> ProductRepository;

    public BLLProducts(EFRepository<Product> Repository)
    {
        ProductRepository = Repository;
    }

    public ICollection<Product> getAll()
    {
        return ProductRepository.All().ToList();
    }
}
公共类BLLProducts
{
i存储产品库;
公共BLL产品(电子存储库)
{
ProductRepository=存储库;
}
公共ICollection getAll()
{
返回ProductRepository.All().ToList();
}
}
在不创建存储库/上下文的情况下,如何从控制器或unitTest启动
BLLProduct
类?所以我可以在这里保留我的抽象概念


我知道我需要用一些简单的注射器,我只是不知道怎么用

从控制器的角度来看,这只是将
BLLProducts
注入其中的问题,如下所示:

// constructor
public HomeController(BLLProducts products) {
    this.products = products;
}
从单元测试的角度来看,让控制器依赖于具体的类是次优的(这违反了规则)。这是次优的,因为您现在需要创建一个
BLLProducts
实例,并使用
DbContext
对其进行实例化,但此DbContext特定于实体框架,它依赖于数据库。这使得测试更加困难和缓慢。您希望单元测试在没有数据库的情况下运行

因此,解决这个问题的方法是将这个
BLLProducts
类隐藏在抽象后面。一种简单的方法是从此类中提取接口:

public interface IBLLProducts {
    ICollection<Product> getAll();
}
您需要在Simple Injector中注册此
IBLLProducts
接口:

container.Register<IBBLProducts, BLLProducts>();
container.Register();

整个模型仍有一些缺点。例如,尽管Simple Injector可以为您创建和处理DbContext,但您在哪里调用SubmitChanges?在web请求结束时执行此操作是一个非常糟糕的主意。我找到的唯一方便的解决方案是转向更坚固的体系结构。例如,看一看。

非常感谢!您会向我推荐哪种接近我当前架构的可靠架构?(
BLL
正在通过存储库与
DAL
对话,
MVC
正在使用简单注射器与
BLL
对话)@jony89:学习5个坚实的原则。与不同的体系结构样式(如3层体系结构)相比,它们为您提供了更重要的指导。对抽象进行编程,限制类的职责,并防止在添加功能时必须更改类。
container.Register<IBBLProducts, BLLProducts>();