c# – 依赖注入解析和单元测试

前端之家收集整理的这篇文章主要介绍了c# – 依赖注入解析和单元测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试学习依赖注入,并在单元测试应用程序时遇到了问题.

我正在编写一个控制台应用程序,并在Main()中创建并初始化容器,它在Program.Container中作为get属性提供,因此在我的应用程序的任何地方我都可以调用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.

当您一直使用依赖注入时,您将不需要将大量参数传递给对象.每个对象的构造函数应仅具有它本身直接使用的那些依赖项作为参数 – 它不会知道其直接依赖项的传递依赖性.

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

一些链接获取更多信息:

> http://martinfowler.com/articles/injection.html
> http://www.youtube.com/watch?v=RlfLCWKxHJ0 – 关于传递物体的问题从19:20回答“关于DI的神话”

原文链接:https://www.f2er.com/csharp/243435.html

猜你在找的C#相关文章