Suppose I have an utility (e.g. a logger) that might be used by every class in my app. I want the logger to be able to save the information about the client type that uses the logger i.e. if a StockProvider
wants to log a message, the logger should append the StockProvider
class name along with the log message. And the StockProvider
has the logger passed via constructor like
public StockProvider (ILogger logger) {}
so it can use the logger in its methods.
I know it's easiest to have the type information passed every time logger is used, like logger.Log (GetType(), msg)
. What I want is the logger to have that client type information in its state instead of having to pass that type info to logger methods so that calls to Log
result in the message being appended the type name. E.g. passing it with a constructor like
class Logger : ILogger {
public Logger (Type clientType) {
this.type = clientType;
}
public void Log(string msg)
{ Console.WriteLine(this.type.FullName + msg); }
}
would work as then inside StockProvider
I could just say
logger.Log (msg)
So the question is: am I able to register Logger
in such a generic way that it receives the clientType
of the client that requests the logger whether it is StockProvider
or any other client type?
Please notice that I used the logger just as an example of some class that might be widely used in the code. It might also be a kind of event publisher that would want to know who triggers an event