使用Castle Windsor注入日志记录依赖项

Arn*_*Das 1 .net c# castle-windsor

我试图将Castle Windsor的日志依赖注入我的代码.更准确地说,每当类中的方法抛出错误或应用程序流进入方法时,它只需登录到文件中.如何通过写任何东西来做到这一点

logger.Debug("Error code");
Run Code Online (Sandbox Code Playgroud)

在每个方法明确的方法中.假设我们在每个类或方法上添加属性以利用日志记录工具.

提前致谢.

jas*_*son 5

使用Castle Windsor 的拦截设施.

所以标记你的课程

[Interceptor(typeof(UnhandledExceptionLogger))]
Run Code Online (Sandbox Code Playgroud)

并创建一个UnhandledExceptionLogger实现的类IInterceptor.大致:

public void Intercept(IInvocation invocation) {
    try {                
        invocation.Proceed();
    }
    catch (Exception e) {
        // log the exception e
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后当Castle Windsor创建一个用此标记的类的实例时Interceptor,它将创建一个代理,它包装上述try/catch log/rethrow块中的所有方法调用.