考虑这个类具有这两个构造函数:
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/