.NET Core:在方法之前和之后执行的属性 [英] .NET Core: attributes that execute before and after method

查看:68
本文介绍了.NET Core:在方法之前和之后执行的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,可以使用 AspectJ 在执行方法之前和之后添加行为,使用 方法注释.由于 C# 属性似乎非常相似,我想知道是否有可能实现类似的行为.我正在查看几个教程和其他来源(123),但他们都没有帮助我.

In Java, it is possible to use AspectJ for adding behavior before and after executing a method, using method annotations. Since C# Attributes seem to be very similar, I was wondering whether it would be possible to achieve similar behavior. I was looking in several tutorials and other sources (1, 2, 3), but none of them helped me.

我想也许我可以通过将代码插入到 Attribute 构造函数中并使其成为可抛弃的来模仿行为,就像这样:

I thought that maybe I could be able to mimic the behavior by inserting the code into Attribute constructor and making it disposable, like this:

[AttributeUsage(AttributeTargets.Method)]
public class MyWritingAttribute : Attribute, IDisposable
{
    public MyWritingAttribute()
    {
        Console.WriteLine("Attribute created");
    }

    public void Dispose()
    {
        Console.WriteLine("Attribute disposed");
    }
}

然而,当使用这样的属性时,只有 Hello world! 显示在控制台中:

However, when using the attribute like this, only Hello world! got displayed in the console:

class Program
{
    static void Main(string[] args)
    {
        SayHelloWorld();
        Console.ReadLine();
    }

    [MyWriting]
    private static void SayHelloWorld()
    {
        Console.WriteLine("Hello World!");
    }
}

我在想,也许在属性中无法访问 Console,但即使用 throw new Exception() 表达式替换它,也没有抛出异常.EF 的 StringLengthAttribute 怎么可能工作,但我的属性甚至没有实例化?以及如何让属性在装饰方法之前和之后运行?

I was thinking that maybe Console is not reachable in the attribute, but even when replacing it with throw new Exception() expressions, no exception was thrown. How is it possible that StringLengthAttribute from EF works, but my attribute is not even instantiated? And how do I make the attribute run before and after the decorated method?

推荐答案

就像 Java 和 AspectJ 一样,您需要单独的 AoP 工具来在 .NET 中注入这样的代码.

Just like with Java and AspectJ, you need separate AoP tooling to inject code like this in .NET.

PostSharp 就是这样一种工具,可能是最著名的工具.我相信他们从第 5 版开始就支持 .NET 核心.

PostSharp is one such tool, probably the best known. I belive they have support for .NET core since version 5.

这篇关于.NET Core:在方法之前和之后执行的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆