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

时间:2017-09-04 03:59:58

标签: c# .net-core aop

我正在将我的应用程序从.Net Framework 4.5.1迁移到Dot Net Core。 我使用RealProxy类来记录BeforeExecute和AfterExecute上的用户信息和参数(如此link

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

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

1 个答案:

答案 0 :(得分:7)

正如我在RealProxy in dotnet core?中已经回答的那样,RealProxy并不存在于.NET Core中。

另一种选择是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");
    }
}

因此,如果我们有一个带有相应接口的示例类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();
}

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

相关问题