c# - 依赖注入(inject)解析和单元测试

标签 c# .net unit-testing dependency-injection ioc-container

我正在尝试学习依赖注入(inject),但在对应用程序进行单元测试时遇到了一个问题。

我正在编写一个控制台应用程序,容器是在 Main() 中创建和初始化的,它以 get-property 的形式提供。在 Program.Container ,所以在我的应用程序中的任何地方我都可以调用 Program.Container.Resolve<..>() .

我有一个像这样的 ServiceValidator 类:

public class ServiceValidator
{
    private readonly IConfiguration _configuration;
    private readonly IService _service;

    public ServiceValidator(IConfiguration configuration, IService service)
    {
        _configuration = configuration;
        _service = service;
    }

在我使用的另一个类中

ServiceValidator serviceValidator = Program.Container.Resolve<ServiceValidator>();
serviceValidator.VerifyVersion();

这是对 Program.Container.Resolve 的调用这导致我在单元测试中出现问题,因为它尚未设置。

在容器上调用 resolve 是一种不好的做法吗?我可以在 Main() 中创建 ServiceValidator 实例并传递对象,但这看起来很愚蠢,因为它会为刚传递给下一个方法的对象产生大量参数。

所以我想在一个类中调用 Resolve 是可以接受的,但是容器必须为单元测试配置。我应该怎么做,我应该将容器移动到 Program 类之外的另一个地方吗?你会推荐什么?

如果重要的话,我正在使用 Unity 和 C#

谢谢:-)

最佳答案

Is that a bad practice, to call resolve on the container? I could create the ServiceValidator instance in Main() and pass the object around, but that seems stupid as it would cause lots of parameters for the objects that are just passed around to the next method.

当你一直使用依赖注入(inject)时,你就不需要将大量参数传递给对象。每个对象的构造函数应该只有那些它自己直接使用的依赖项作为参数——它不会知道其直接依赖项的传递依赖项。

因此,如果您有一个需要 ServiceValidator 的类 X,那么类 X 将具有一个 ServiceValidator 类型的构造函数参数。然后,如果某个类 Y 使用类 X,则类 Y 将具有类型 X 的构造函数参数。请注意,Y 对 ServiceValidator 一无所知,因此您不需要将 ServiceValidator 从一个类传递到another - 唯一使用它的地方是在构建 X 时,这通常由 DI 框架完成,或者只在手写工厂的一个地方完成。

更多信息的一些链接:

关于c# - 依赖注入(inject)解析和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/820105/

相关文章:

AutoResetEvent 的 C# 线程问题

c# - C#:有关引发适当类型的异常的文章

c# - 并行任务的最大数量是否有一般规则?

unit-testing - PHPUnit - 如何在另一个类的方法中模拟该类?

c# - 有没有办法在 C# 中编写单元测试以确保不会在项目的任何地方调用方法?

c# - 看不到编译器如何使用他为我的闭包创建的类

c# - 获取焦点窗口名称

.net - 在 C# 中按 Start 后,我​​在开始时收到 Source Not found Error

.net - 如何捕获特定的 OleDbException?

unit-testing - 如何为速度模板编写单元测试?