且构网

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

Microsoft Unity接口拦截和构造函数注入之间的区别

更新时间:2021-07-23 22:30:26

拦截和注入是两回事.

拦截通常用于向类中添加横切关注点(例如日志记录),而不必一遍又一遍地实现它们. Unity中的拦截工作原理是生成代理,这些代理接收传入的方法调用,并通过所谓的拦截器管道将其引导,直到调用最终到达原始目标对象为止.

Interception is usually used to add cross-cutting concerns (like logging) to classes without having to implement them over and over again. Interception in Unity works by generating proxies that receive incoming method calls and channel them through a pipeline of so called interceptors until the call finally reaches the original target object.

这两篇文章介绍了Unity拦截的工作原理.

These two articles introduce how interception with Unity works.

Unity中的拦截器

使用Unity拦截功能

构造函数注入是实现依赖注入模式的一种方法.这种模式可以告诉您如何构造应用程序以解耦组件.

Constructor injection is one way to implement the Dependency Injection Pattern. It is a pattern that tells you how to structure your application to decouple components.

网络上有很多文章.

控制容器的反转和依赖注入模式

截取和注入完全不同.但是某些依赖注入容器(例如Unity)允许您同时执行这两种操作.您可以使用容器基础结构将依赖项注入类并拦截对这些类的调用.

Interception and injection are something completely different. But some Dependency Injection containers (like Unity) allow you to do both. You can inject dependencies into classes and intercept calls to those classes using the container infrastructure.