且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

依赖注入&使用接口?

更新时间:2023-01-11 10:06:11

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

Letting your application components (the classes that contain the application logic) implement an interface is important, since this promoted the concept of:


编程到接口,而不是实现。

Program to an interface, not an implementation.

这实际上是依赖性倒置原则。这样做可以让您替换,拦截或修饰依赖项,而无需更改此类依赖项的使用者。

This is effectively the Dependency Inversion Principle. Doing so allows you to replace, intercept or decorate dependencies without the need to change consumers of such dependency.

在许多情况下,开发人员将违反 SOLID 但是在类和接口之间进行几乎一对一的映射时。几乎肯定违反的原则之一是开放/封闭原则,因为class有自己的接口,不可能扩展(装饰)一组具有横切关注的类(没有动态代理生成技巧)。

In many cases developers will be violating the SOLID principles however when having an almost one-to-one mapping between classes and an interfaces. One of the principles that is almost certainly violated is the Open/closed principle, because when every class has its own interface, it is not possible to extend (decorate) a set of classes with cross-cutting concerns (without dynamic proxy generation trickery that is).

In在我编写的系统中,我定义了两个通用接口,它们覆盖了业务层的大部分代码。它们被称为 ICommandHandler< TCommand> IQueryHandler< TQuery,TResult>

In the systems I write, I define two generic interfaces that cover the bulk of the code of the business layer. They are called ICommandHandler<TCommand> and an IQueryHandler<TQuery, TResult>:

public interface ICommandHandler<TCommand>
{
    void Handle(TCommand command);
}

public interface IQueryHandler<TQuery, TResult> where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}

除了不必定义多个接口的好副作用外,这样可以很好灵活性和易测性。您可以在此处此处

Besides the nice side effect of not having to define many interfaces, this allows great flexibility and ease of testing. You can read more about it here and here.

取决于在我写的系统上,我也可能使用以下接口:

Depending on the system I write, I might also use interfaces such as:


  • IValidator< T> 用于验证消息

  • ISecurityValidator< T> 用于对消息应用安全限制

  • IRepository< T> ,存储库模式

  • IAuthorizationFilter< T> 用于对 IQueryable< T> 查询进行授权/安全过滤。

  • IValidator<T> for validating messages
  • ISecurityValidator<T> for applying security restrictions on messages
  • IRepository<T>, the repository pattern
  • IAuthorizationFilter<T> for applying authorization/security filtering on IQueryable<T> queries.

取决于在我写的系统上,所有组件的80%到98%之间的某个部分实现了我定义的这些通用接口之一。这使得横切关注的问题应用于那些所谓的 joinpoints 无关紧要。

Depending on the system I write, somewhere between 80% and 98% procent of all components implement one of these generic interfaces I define. This makes applying cross-cutting concerns to those so called joinpoints trivial.