DI Interception vs. AOP

纵然是瞬间 提交于 2019-12-11 11:56:31

问题


From Unity documentation:

Unity interception enables you to effectively capture calls to objects and add additional functionality to the target object. Interception is useful when you want to modify the behavior for individual objects but not the entire class, very much as you would do when using the Decorator pattern. It provides a flexible approach for adding new behaviors to an object at run time.

Since the very same DP is used in Aspect Oriented Programming (see here)

...In the .NET Framework, the most commonly used of these techniques are post-processing and code interception. The former is the technique used by PostSharp and the latter is used by dependency injection (DI) containers such as Castle DynamicProxy and Unity. These tools usually use a design pattern named Decorator or Proxy to perform the code interception.

In these quotations Proxy is used as a synonym of Decorator despite they are very alike there are some differences.

So, my question is: What (and most importantly why) AOP has to be preferred over DI interception? Or is DI interception a better way to augment a object's functionality without changing its implementation? In general, if one should be preferred over the other then why?


回答1:


Here are some of the limitations with using DI container interception:

1) Interception using a DI container is limited to objects that were created using the container.

For example, you might have a factory that you register with your container. Objects that such factory create will not have interception support.

Consider the following code:

public interface IHelperFactory
{
    IHelper CreateHelper();
}

public interface IHelper
{
    void HelpMe();
}

class Helper : IHelper
{
    public void HelpMe()
    {

    }
}

class HelperFactory : IHelperFactory
{
    public IHelper CreateHelper()
    {
        return new Helper();
    }
}

If you register HelperFactory with the container, then the CreateHelper method can be intercepted, however, calls to IHelper.HelpMe will not be intercepted.

2) Another limitation of interception through DI containers is that you cannot intercept private methods unless you change them to become virtual protected methods and use virtual method interceptors, which in turn disallow you to intercept objects registered as instances.

3) (IMO) It might not be a good idea to use a DI container in the first place. See my article here



来源:https://stackoverflow.com/questions/32251755/di-interception-vs-aop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!