且构网

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

注入横切关注点有哪些不同的方法?

更新时间:2023-12-04 18:55:46

装饰器设计模式是实施跨领域关注点的绝佳起点.

The Decorator design pattern is an excellent starting point for implementing cross-cutting concerns.

首先,您需要定义一个对相关服务建模的接口.然后,您可以实现该服务的真正功能,而根本不考虑您的跨领域问题.

First you need to define an interface that models the service in question. Then you implement the real functionality of that service without thinking about your cross-cutting concern at all.

然后您可以随后实现环绕其他实例的装饰类并实现所需的横切关注点.

Then you can subsequently implement decorating classes that wrap around other instances and implement the desired cross-cutting concern.

这种方法可以完全用普通的旧 C# 对象 (POCO) 实现,不需要额外的框架.

This approach can be implemented entirely with Plain Old C# Objects (POCOs) and requires no extra frameworks.

但是,如果您厌倦了编写所有额外的装饰器,则可能需要使用框架.我没有使用显式 AOP 框架的经验,但大多数 DI 容器(例如 Castle Windsor)都提供类似 AOP 的功能功能.

However, if you get tired of writing all the extra decorators, you may want to use a framework. I have no experience with explicit AOP frameworks, but most DI Containers such as Castle Windsor offer AOP-like features.

这是一个使用装饰器的例子.假设您有以下界面:

Here's an example of using Decorators. Let's say that you have the following interface:

public interface IMyInterface
{
    void DoStuff(string s);
}

您的具体实现可能会做一些非常有趣的事情,例如将字符串写入控制台:

Your concrete implementation may do something very interesting, such as writing the string to the Console:

public class ConsoleThing : IMyInterface
{
    public void DoStuff(string s)
    {
        Console.WriteLine(s);
    }
}

如果你想记录 DoStuff 操作,你现在可以实现一个日志装饰器:

If you wish to log the DoStuff operation, you can now implement a logging Decorator:

public class LoggingThing : IMyInterface
{
    private readonly IMyInterface innerThing;

    public LoggingThing(IMyInterface innerThing)
    {
        this.innerThing = innerThing;
    }

    public void DoStuff(string s)
    {
        this.innerThing.DoStuff(s);
        Log.Write("DoStuff", s);
    }
}

您可以继续编写新的装饰器,例如缓存装饰器或实现安全性等的装饰器,并将它们相互包裹起来.

You can keep writing new Decorators, like a caching Decorator or one that implements security and so on, and just wrap them around each other.

注意:我很少推荐静态接口,所以 Log.Write 接口不是推荐的,只是作为占位符的意思.在实际实现中,我会向 LoggingThing 中注入某种 ILogger 接口.

Note: I rarely recommend static interfaces, so the Log.Write interface is not a recommendation, but merely mean as a placeholder. In a real implemetation, I'd inject some kind of ILogger interface into LoggingThing.