【发布时间】:2013-01-21 19:37:48
【问题描述】:
我是 DI 模式的新手……现在刚刚学习。我得到了一个使用统一的构造函数注入代码。这是代码。
public class CustomerService
{
public CustomerService(LoggingService myServiceInstance)
{
// work with the dependent instance
myServiceInstance.WriteToLog("SomeValue");
}
}
IUnityContainer uContainer = new UnityContainer();
CustomerService myInstance = uContainer.Resolve<CustomerService>();
在这里我们可以看到 CustomerService ctor 正在寻找 LoggingService 实例,但是在这里当我们通过解析创建 CustomerService 的实例时,我们并没有传递 LoggingService 的实例。所以告诉我怎么会起作用。任何人都用小的完整示例代码来解释它。谢谢
【问题讨论】:
-
您的要求并不完全清楚。据推测 LoggingService 将是一个接口,而不是具体类型,并且当您引导容器时,您将为它提供从 LoggingService 接口到具体类型的映射。当您要求容器解析 CustomerService 时,它会看到构造函数采用 LoggingService 接口并尝试解决该接口,然后将 LoggingService 的实例传递给构造函数。
-
您真正需要的是 ICustomerService 和 ILoggingService 接口,而这些正是您要解决的。当您引导容器时,您将创建从 ICustomerService 到 CustomerService 和 ILoggingService 到 LoggingService 的映射
-
你能否提供完整的小代码,这样我可以更好地可视化,因为我在 DI 方面很弱。
标签: c# dependency-injection unity-container