如何使用Unity进行依赖注入(简单的例子)

本文关键字:简单 注入 Unity 何使用 依赖 | 更新日期: 2023-09-27 18:14:00

用下面两个构造函数考虑这个类:

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;
    }
}
我使用第二个构造函数模拟单元测试的依赖项。

有时候依赖关系太多,所以注入构造函数会有太多的参数。

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

我如何重构这段代码来使用Unity ?

(阅读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());

我猜你想在两种情况下注入依赖:在(单元)测试中(例如使用RhinoMocks)和实际实现(使用Unity)。重构意味着在这种情况下,您应该删除(DocumentService类的)第一个构造函数。依赖中需要的配置应该加载到依赖本身中:DocumentDbService, DirectoryInfo, FileInfo。更多信息(如依赖注入生命周期)和一些例子可以在MSDN上获得,参见https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx