interface - 依赖注入(inject)和使用接口(interface)?

标签 interface dependency-injection

我注意到很多开发人员为 定义了一个接口(interface)。每个 将使用 DI 框架注入(inject)的类。为每个类定义接口(interface)有什么好处?

最佳答案

让您的应用程序组件(包含应用程序逻辑的类)实现接口(interface)很重要,因为这促进了以下概念:

Program to an interface, not an implementation.


这实际上是 Dependency Inversion Principle .这样做允许您替换、拦截或装饰依赖项,而无需更改此类依赖项的使用者。
在许多情况下,开发人员将违反 SOLID然而,当类和接口(interface)之间几乎是一对一的映射时。几乎可以肯定违反的原则之一是 Open/closed principle ,因为当每个类都有自己的接口(interface)时,不可能扩展(装饰)一组具有横切关注点的类(即没有动态代理生成技巧)。
在我编写的系统中,我定义了两个通用接口(interface),涵盖了业务层的大部分代码。他们被称为 ICommandHandler<TCommand>IQueryHandler<TQuery, TResult> :
public interface ICommandHandler<TCommand>
{
    void Handle(TCommand command);
}

public interface IQueryHandler<TQuery, TResult> where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}
除了不必定义许多接口(interface)的好处之外,这还提供了极大的灵 active 和易于测试。您可以阅读更多信息 herehere .
根据我编写的系统,我还可能使用以下接口(interface):
  • IValidator<T>用于验证消息
  • ISecurityValidator<T>对消息应用安全限制
  • IRepository<T> ,存储库模式
  • IAuthorizationFilter<T>用于在 IQueryable<T> 上应用授权/安全过滤查询。

  • 根据我编写的系统,80% 到 98% 的所有组件都实现了我定义的这些通用接口(interface)之一。这使得将横切关注点应用于所谓的 joinpoints琐碎的。

    关于interface - 依赖注入(inject)和使用接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9446502/

    相关文章:

    language-agnostic - "program to an interface"是什么意思?

    java - 任何人都可以解释以下代码的工作......?

    java - 为什么createStatement方法是在Connection接口(interface)而不是Statement接口(interface)下声明的?

    c# - MediatR 错误 : Register your handlers with the container

    javascript - 缩小 httpInterceptor AngularJS $injector 错误

    PHP、OOP 接口(interface)和抽象

    ios - 是否有在没有不可访问的 Interface Builder 的情况下编写 GUI 的教程?

    java - 使用注释处理延迟绑定(bind)到 Dagger2 Graph

    c# - 在简单注入(inject)器中延迟创建实例

    c# - 以 SOLID 方式使用 DbContext