I have a c# web service. When I get a new request I create a logging instance. I have many other instances of other classes to process the request and I want them to log as well. What is the best way to share logging instance without passing it in constructors or properties ?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Singleton Pattern is an anti-pattern; I can not think of many instances where it should be used or recommended, including in this instance, for logging.
How we handle logging: A logging instance is injected into all classes that need it via constructor injection. For example:
The logging instance injected can either be a new instance each time, or if you are bent on having a single instance logger it can be created once and passed through as needed.
However: I strongly recommend the first option, using DI to construct your classes using the Composition Root pattern. I also recommend using a logging framework, such as NLog or log4net. These are configurable and easy to use with emails, event viewer, files, etc. and work in multi threaded environments.
We have our own definition of ILogger which has Trace, Warn, Info, Exception, etc., and then implemented this interface using NLog. This means that we can easily change how we log by creating a new implementation of ILogger and then making a simple DI config update. This is one logging solution that has worked really well for us so far.