Dependency Injection & using interfaces?

2020-02-17 03:19发布

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?

2条回答
Animai°情兽
2楼-- · 2020-02-17 03:48

This blog entry has a lot of the answers you are looking for: http://benpryor.com/blog/2006/08/23/java-advantages-of-interfaces/

If you don't design to interfaces, you are going to be hamstrung when it comes time to refactor your code and/or add enhancements. Using a DI framework is not really at issue when it comes to designing to an interface. What DI gives you is late-binding and much better ability to write unit tests.

查看更多
3楼-- · 2020-02-17 03:57

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.

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 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> 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.

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.

查看更多
登录 后发表回答