Inject logging dependency with Castle Windsor

梦想的初衷 提交于 2019-12-08 03:30:12

问题


I was trying to inject logging dependency by Castle Windsor to my code. More precisely, whenever a method in a class throws an error or application flow enters into a method it simply logs into a file. How to do this by writing nothing like

logger.Debug("Error code");

in the methods explicitly for each of the methods. Suppose we add attribute on each of the class or methods to leverage the logging facility for that.

Thanks in advance.


回答1:


Use the interceptor facility in Castle Windsor.

So mark your class with

[Interceptor(typeof(UnhandledExceptionLogger))]

and create a class UnhandledExceptionLogger that implements IInterceptor. Roughly:

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

and then when Castle Windsor creates an instance of your class marked with this Interceptor, it will create a proxy that wraps all methods invocations in the above try/catch log/rethrow block.



来源:https://stackoverflow.com/questions/7046399/inject-logging-dependency-with-castle-windsor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!