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
You can use the Singleton Pattern to ensure that there is only a single instance of your logging object across the system.
Passing the logging object into the Constructor or as a property will actually make your code easier to test, depending on how you implement the Singleton pattern. Logging is one of those annoying cross-cutting concerns that always has trade-offs.
Singleton Pattern.
That is, a class with a private constructor. You use a public static method to create only one instance of the class and return the object.
edit: also worth noting that you will need to put this class in its own project so that it can be referenced by all classes.
Well, you could make your logging class contain static methods which do the actual writing into memory/flushing to disk. You could also look into the Singleton Pattern
Usually it's not a problem to create a new instance of your logger in each class. Log4Net logger constructor takes a type as a parameter to give you better logs.
Often some sort of static class / property is used to share an object without needing to pass references everywhere, for example:
Usage:
Often this (or at least variations on this) are referred to as the singleton pattern.
There are many variations on the above, for example the following slight variation is more common than the above in logging frameworks:
Usage:
Use a static field (I assume C# supports theses). The syntax should be similar to this:
and just use that whenever you need to log something in the class.