且构网

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

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

更新时间:2023-12-04 19:04:34

装饰设计模式是一个很好的起点实现横切关注点。

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#对象(波苏斯)来实现,并且不需要额外的框架。

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

不过,如果你厌倦了写这些额外的装饰,你可能需要使用一个框架。我有一个明确的AOP框架没有经验,但大多数DI容器,如温莎城堡 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接口不是一个建议,但仅仅意味着作为占位符。在实际的实现,我会注入某种ILogger接口到LoggingThing。

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.