在.NET 2.1的核心使用AOP记录

问题描述 投票:3回答:2

我想要实现AOP在我的.NET 2.1的核心解决方案的记录。我以前从未使用过它,我一直在网上找,并不能似乎看到了使用它与酷睿2有谁知道我怎么会去了解这个人的例子?

例如什么包使用AOP和有任何示例代码让我开始?即时通讯使用内置的DI与.NET的核心,所以我不需要担心这个问题的一部分。

c# logging asp.net-core aop asp.net-core-2.1
2个回答
6
投票

微软DI不提供预付款的情况,如拦截或装饰(有使用微软DI装饰解决方法:https://medium.com/@willie.tetlow/net-core-dependency-injection-decorator-workaround-664cd3ec1246)。

您可以通过使用Autofac(https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html)或动态代理简单的喷油器实现AOP。两者有一个非常好的文档。简单的注射器没有一个出来拦截现成的解决方案,因为他们的设计规则,但你可以为它(http://simpleinjector.readthedocs.io/en/latest/aop.html)添加一个扩展。

下面是从官方文档SI基本的AOP场景:(http://simpleinjector.readthedocs.io/en/latest/InterceptionExtensions.html):

//Add registration to the composition root
container.InterceptWith<MonitoringInterceptor>(serviceType => serviceType.Name.EndsWith("Repository"));`

// Here is an example of an interceptor implementation.
// NOTE: Interceptors must implement the IInterceptor interface:
private class MonitoringInterceptor : IInterceptor {
    private readonly ILogger logger;

  public MonitoringInterceptor(ILogger logger) {
        this.logger = logger;
    }

    public void Intercept(IInvocation invocation) {
        var watch = Stopwatch.StartNew();

        // Calls the decorated instance.
        invocation.Proceed();

        var decoratedType = invocation.InvocationTarget.GetType();

        this.logger.Log(string.Format("{0} executed in {1} ms.",
            decoratedType.Name, watch.ElapsedMilliseconds));
    }
}

3
投票

Disclaimer: I am the producer of this solution

微软并没有提供AOP解掉净芯盒。不过,我已经产生了第三方项目,这可能会有帮助。它直接与核心网,并通过在应用程序中ServiceCollection注册插头英寸

什么微软确实提供了一个名为System.Runtime.DispatchProxy库,可以用来为您的类创建代理对象。然而,这个代理心不是特别有用或功能丰富自身,并且将需要很多额外的代码来得到的东西,是与城堡代理(众所周知的动态代理库)的水平

考虑到这一点,我创建了包裹DispatchProxy成可以在应用程序启动时ServiceCollection配置过程中很容易注入的代码库。关键是有一个方法来创建属性和配对的拦截器,可以应用到你的方法。然后,属性是代理包装过程中读取和相关拦截器被调用。

这是一个例子拦截属性

public class ConsoleLogAttribute : MethodInterceptorAttribute
{
}

这是一个例子拦截器类

public class ConsoleLogInterceptor : MethodInterceptor
{
    public override void BeforeInvoke(IInterceptionContext interceptionContext)
    {
        Console.WriteLine($"Method executing: {interceptionContext.CurrentMethod.Name}");
    }

    public override void AfterInvoke(IInterceptionContext interceptionContext, object methodResult)
    {
        Console.WriteLine($"Method executed: {interceptionContext.CurrentMethod.Name}");
    }
}

这是它会如何应用到你的方法

[ConsoleLog]
public void TestMethod()
{
}

然后终于,这是它如何被添加到您的ServiceCollection配置(假设你想代理类被称为[TestClass中]:

public void ConfigureServices(IServiceCollection services)
{
    // Configure Simple Proxy
    services.EnableSimpleProxy(p => p.AddInterceptor<ConsoleLogAttribute, ConsoleLogInterceptor>());

    // Configure your services using the Extension Methods
    services.AddTransientWithProxy<ITestClass, TestClass>();
}

看看这个项目的GitHub:https://github.com/f135ta/SimpleProxy

© www.soinside.com 2019 - 2024. All rights reserved.