DI中的接口注入章节

时间:2015-01-09 09:02:07

标签: interface dependency-injection

我刚开始学习什么是依赖注入和InversionOfControll。但我不能得到一件事。当我定义一些描述方法需要实现的接口时,接口注入就开始了。并且该方法获取某个类的实例作为参数,然后在实现接口的类中只描述该方法的主体?

1 个答案:

答案 0 :(得分:1)

接口只是一个定义类应该实现的公共成员的契约。它不控制实际的实现 - 你需要一个具体的类来做到这一点。

// This is only a contract that defines what members
// all concrete types must implement.
public interface ISomeType
{
    void DoSomething();
}

// This class implements the interface. Therefore, it must
// have all of the methods the contract specifies. In some
// languages, this can be done implicitly just by adding the
// member, but it usually must be public.
public class SomeType : ISomeType
{
    public void DoSomething()
    {
        Console.WriteLine("Hello World");
    }
}

当你创建一个类实现一个接口时,它隐含意味着可以将类的实例强制转换为接口类型。

ISomeType x = new SomeType();

依赖注入利用了这种行为。您通常在映射中同时定义接口类型和具体实现。

container.For<ISomeType>().Use<SomeType>();

然后,当声明服务将ISomeType作为构造函数参数时,该映射用于确定要创建实例的具体类型。

public class SomeService : ISomeService
{
    private readonly ISomeType someType;

    public SomeService(ISomeType someType)
    {
        if (someType == null) throw new ArgumentNullException("someType");
        this.someType = someType;
    }
}

推荐的方法是允许DI容器在组成整个对象图时隐式执行此操作(在Composition Root中),但也可以明确地执行此操作(并且它是一个更好的示例) :

ISomeService = container.GetInstance<ISomeService>();

假设容器已配置为将ISomeService映射到SomeService(就像之前我用ISomeType所示),这一行代码将创建SomeService的实例并自动将SomeType的实例注入其构造函数。

尽管如此,很难在一个简单的例子中看到这一点。依赖注入适用于具有多种类型的复杂应用程序。当应用程序很复杂时,它简化了事情,但是当应用程序很简单时,它会使事情变得更复杂。