簡體   English   中英

如何使用Unity進行依賴項注入(簡單示例)

[英]How to use Unity for dependency injection (simple example)

考慮以下兩個構造函數的類:

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文檔之后,仍然不確定如何在我的代碼中正確使用它。)

假設您想簡化單元測試代碼,以避免在每個測試中手動設置每個依賴項:

您可以設置容器並在其中添加所有必需的模擬,然后為測試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/zh-cn/library/dn178463(v=pandp.30).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM