dependency-injection - 为什么 AOP 和 DI 不经常一起使用

标签 dependency-injection aop

我对这条线感到困惑

Aspect-Oriented Programming and Dependency Injection are very different concepts, but there are limited cases where they fit well together.

从这个网站

http://www.postsharp.net/blog/post/Aspect-Oriented-Programming-vs-Dependency-Injection

我理解 DI 相对于 AOP 的优势,但为什么它们没有更频繁地一起使用?为什么它们只能在有限的情况下组合在一起?是不是因为 AOP 的编译方式,导致两者都很难使用?

最佳答案

您如何定义“有限情况”?我自己总是同时使用 AOP 和 DI。

应用AOP基本上有3种方式,分别是:

  1. 使用 PostSharp 等代码编织工具。
  2. 使用 CaSTLe Dynamic Proxy 等动态拦截工具。
  3. 使用装饰器。

将 DI 与代码编织工具一起使用并不能很好地混合和匹配,我认为这就是 Postsharp 站点声明“它们可以很好地结合在一起的有限情况”的原因。它不能混合和匹配的原因之一是因为依赖注入(inject)是关于松散耦合的,而代码编织在编译时将代码和方面硬耦合在一起。从 DI 的角度来看,代码编织成为一种反模式。在 our book 的第 11.2 节中, Mark我把这个论点说得很清楚了。总之,我们声明:

The aim of DI is to manage Volatile Dependencies by introducing Seams into your application. Theis enables you to centralize the composition of your object graphs inside the Composition Root.

This is the complete opposite of hat you achieve when applying compile-time weaving: is causes Volatile Dependencies to be coupled to your code at compile-time. This makes it impossible to use proper DI techniques and to safely compose complete object graphs in the application's Composition Root. It's for this reason that we say that compile-time weaving is the opposite of DI–using compile-time weaving on Volatile Dependencies is an anti-pattern. [page 355]

但是,如果您使用动态拦截,这意味着通过动态生成装饰器在运行时应用横切关注点,它可以很好地与 DI 配合使用,并且可以轻松地与大多数 DI 库集成,并且也可以在以下情况下完成使用 Pure DI ,这是我们在 11.1 节中演示的内容。

我个人的偏好是使用装饰器。 My systemsdesigned around一个few well defined通用抽象,这使我能够在几乎所有对我的系统重要的地方应用横切关注点。这让我在极少数情况下有几个地方装饰器不能很好地工作,但这几乎总是由设计缺陷引起的。无论是由于我作为开发人员的局限性,还是由于 .NET 框架或其他工具的设计缺陷。一个著名的设计缺陷是 INotifyPropertyChanged 接口(interface)。您可能已经猜到了,但在我们的书中我们详细描述了这种方法。我们用完整的一章 (10) 来讨论这个主题。

关于dependency-injection - 为什么 AOP 和 DI 不经常一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24749653/

相关文章:

java - 切入点不适用于通用接口(interface)

java - 尚未应用带有 AspectJ 抛出建议的删除向导指标

java - 根据返回值调用切面

unit-testing - 如何在函数式编程中编写好的单元测试

java - Injector.getInstance(..) 为单例返回一个新实例

java - 如何使用 DI 基于 String 动态选择要执行的服务?

java - 理解 Play 2.4 依赖注入(inject)

Android - 运行时使用 Dagger 创建对象

Spring AOP : advice is not triggered

Spring AOP : Getting parameters of the pointcut annotation