Dependency Injection & using interfaces?
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 messagesISecurityValidator<T>
for applying security restrictions on messagesIRepository<T>
, the repository patternIAuthorizationFilter<T>
for applying authorization/security filtering onIQueryable<T>
queries.
Depending on the system I write, somewhere between 80% and 98% of all components implement one of these generic interfaces I define. This makes applying cross-cutting concerns to those so called joinpoints trivial.
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.