Dotnet核心中的AOP:Dotnet核心中具有Real Proxy的动态代理

Pou*_*mie 19 c# aop .net-core

我正在将我的应用程序从.Net Framework 4.5.1迁移到Dot Net Core.我使用RealProxy Class在BeforeExecute和AfterExecute上记录用户信息和参数(比如这个链接)

现在似乎Dot core.Plus中没有这样的东西我不想使用第三方.我发现这个链接正在使用Actionfilter,但它不能完成这项工作.

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

Com*_*Guy 10

正如我已经在dotnet核心的RealProxy中回答的那样,.NET中不存在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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public class Calculator : ICalculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • "正如我已经回答过......"为什么你不把这个问题标记为重复呢? (3认同)