本文介绍了依赖注入&使用接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've noticed that a lot of developers define an interface for EVERY class that is going to be injected using DI framework. What are the advantages of defining Interfaces for every class?

推荐答案

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

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

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

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.

在许多情况下,开发人员将违反但是在类和接口之间进行几乎一对一的映射时。几乎肯定违反的原则之一是,因为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%之间的某个部分实现了我定义的这些通用接口之一。这使得横切关注的问题应用于那些所谓的无关紧要。

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.

这篇关于依赖注入&amp;使用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:23