c# - 如何使用Unity进行依赖注入(inject)(简单示例)

标签 c# unit-testing dependency-injection unity-container

考虑这个类具有这两个构造函数:

public class DocumentService
{
    private IDocumentDbService documentDbService;
    private IDirectoryService directoryService;
    private IFileService fileService;

    // Constructor
    public DocumentService()
    {
          this.documentDbService = new DocumentDbService();
          this.directoryService = new DirectoryInfo();
          this.filService = new FileInfo();
    }

    // Injection Constructor
    public DocumentService(IDocumentDbService dbs, IDirectoryService ds, IFileService fs)
    {
         this.documentDService = dbs;
         this.directoryService = ds;
         this.fileService = fs;
    }
}

我使用第二个构造函数来模拟单元测试的依赖项。

有时依赖项太多,因此注入(inject)构造函数会有太多参数。

所以,我想使用 Unity 依赖注入(inject)。

问题

如何重构此代码以使用 Unity 代替?

(阅读Unity文档后,仍然不确定如何在我的代码中正确使用它。)

最佳答案

假设您想简化单元测试代码以避免在每个测试中手动设置每个依赖项:

您可以设置容器并在其中添加所有必要的模拟,然后Resolve您为测试类:

 // that initialization can be shared
 var container = new UnityContainer();
 // register all mocks (i.e. created with Moq)
 container.RegisterInstnce<IDocumentDbService>(Mock.Of<IDocumentDbService> ());

 // resolve your class under test 
 var documentService = container.Resolve<DocumentService>();

 Assert.AreEqual(42, documentService.GetSomething());

关于c# - 如何使用Unity进行依赖注入(inject)(简单示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32702085/

相关文章:

java - 有没有一种使用 Hamcrest 匹配字段的简单方法?

javascript - 无法将指令作为 AngularJS 中的依赖项注入(inject)

c# - 从 windbg 的 clrstack 输出中获取对象详细信息

java - 如何在 Play Framework 中声明第二个数据库进行测试?

c# - 保存和加载图像 SQLite C#

unit-testing - 为什么不在单元测试中访问数据库?

dependency-injection - 依赖注入(inject)和/vs 全局单例

unit-testing - Pester Mock 不适用于使用脚本 block 的 Invoke-Command

c# - 使用 DapperExtensions 比较两个字段的谓词

c# - AutoMapper ProjectTo 与单个实体?