Dotnet 核心中的 AOP:Dotnet 核心中使用真实代理的动态代理

AOP in Dotnet core : Dynamic Proxy with Real Proxy in Dotnet core

我正在将我的应用程序从 .Net Framework 4.5.1 迁移到 Dot Net Core。 我正在使用 RealProxy Class for logging user information and parameters on BeforeExecute and AfterExecute ( like this link)

现在 Dot 中似乎没有这样的东西 core.Plus 我不想使用第三个 parties.I 发现这个 link 正在使用 Actionfilter 但它不会完成任务。

我的问题是如何在 Dot net Core 中实现动态代理?RealProxy Class 有替代方案吗?

正如我在 中回答的那样,.NET Core 中不存在 RealProxy。

另一种选择是 DispatchProxy,这里有一个很好的例子:http://www.c-sharpcorner.com/article/aspect-oriented-programming-in-c-sharp-using-dispatchproxy/

如果我们简化代码,这就是我们得到的:

public class LoggingDecorator<T> : DispatchProxy
{
    private T _decorated;

    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        try
        {
            LogBefore(targetMethod, args);

            var result = targetMethod.Invoke(_decorated, args);

            LogAfter(targetMethod, args, result);
            return result;
        }
        catch (Exception ex) when (ex is TargetInvocationException)
        {
            LogException(ex.InnerException ?? ex, targetMethod);
            throw ex.InnerException ?? ex;
        }
    }

    public static T Create(T decorated)
    {
        object proxy = Create<T, LoggingDecorator<T>>();
        ((LoggingDecorator<T>)proxy).SetParameters(decorated);

        return (T)proxy;
    }

    private void SetParameters(T decorated)
    {
        if (decorated == null)
        {
            throw new ArgumentNullException(nameof(decorated));
        }
        _decorated = decorated;
    }

    private void LogException(Exception exception, MethodInfo methodInfo = null)
    {
        Console.WriteLine($"Class {_decorated.GetType().FullName}, Method {methodInfo.Name} threw exception:\n{exception}");
    }

    private void LogAfter(MethodInfo methodInfo, object[] args, object result)
    {
        Console.WriteLine($"Class {_decorated.GetType().FullName}, Method {methodInfo.Name} executed, Output: {result}");
    }

    private void LogBefore(MethodInfo methodInfo, object[] args)
    {
        Console.WriteLine($"Class {_decorated.GetType().FullName}, Method {methodInfo.Name} is executing");
    }
}

因此,如果我们有一个示例 class Calculator 具有相应的接口(此处未显示):

public class Calculator : ICalculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

我们可以这样简单地使用它

static void Main(string[] args)
{
    var decoratedCalculator = LoggingDecorator<ICalculator>.Create(new Calculator());
    decoratedCalculator.Add(3, 5);
    Console.ReadKey();
}

您将获得所需的日志记录。