我想在我的 .NET Core 2.1 解决方案中为日志记录实现 AOP。我以前从未使用过它,我一直在网上查找,但似乎看不到有人将它与 Core 2 一起使用的任何示例。有谁知道我将如何处理这个问题?
例如,AOP 使用哪些包?有任何示例代码可以帮助我入门吗?我将内置的 DI 与 .net 核心一起使用,所以我不需要担心那部分。
最佳答案
Microsoft DI 不提供高级方案,例如拦截器或装饰器(使用 Microsoft DI 的装饰器有一个解决方法:https://medium.com/@willie.tetlow/net-core-dependency-injection-decorator-workaround-664cd3ec1246)。
您可以使用 Autofac ( https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html ) 或带有动态代理的简单注入(inject)器来实现 AOP。两者都有非常好的文档。由于其设计规则,简单注入(inject)器没有开箱即用的拦截解决方案,但您可以为其添加扩展(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));
}
}
关于c# - 在 .NET Core 2.1 中使用 AOP 进行日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51783365/