【发布时间】:2019-02-28 06:23:38
【问题描述】:
我试图理解基于构造函数的依赖注入的概念。我已经看到了一些使用接口的constructor based dependency injection 的代码示例。在代码 sn-p 中,我看到服务类构造函数需要 interface 类型的参数,但是在创建服务类对象时,传递了实现该接口的类的实例。那么如何在运行时将类的类型转换为接口的类型,或者还有其他什么?
幕后发生了什么?
让我分享一些示例代码 -
界面-
要实现的简单接口
namespace constructor_di
{
interface IRepoInterface
{
string test();
}
}
存储库 -
Repository 类实现接口
namespace constructor_di
{
class Repository : IRepoInterface
{
public string test()
{
return "Test String";
}
}
}
服务-
服务类期望在创建对象时传递IRepoInterface
namespace constructor_di
{
class Service
{
private readonly IRepoInterface _repo;
public Service(IRepoInterface repoInterface)
{
_repo = repoInterface;
}
}
}
程序启动 -
在这里创建服务类的实例
namespace constructor_di
{
class Program
{
static void Main(string[] args)
{
Service obj = new Service(new Repository());
}
}
}
【问题讨论】:
-
将对象实例作为参数传递给需要接口类型参数的方法是关于协方差(用更具体的类型代替一般类型),与 DI 无关.它的用途之一是在 DI 中,从某种意义上说,您可以让一个模拟对象实现相同的接口并传递它,而不是实际的对象。看看这里:devblogs.microsoft.com/csharpfaq/…
标签: c# oop dependency-injection