Need some Design suggestion in C#
I have a LOG class which uses Microsoft Enterprise Logging. As per my initial design, this was a Static Class and was using "App.Config".
Problem came when I have to use this class as part of my Class Library which will be deployed in GAC. Since the class libraries don't have an App.Config, I have to use my calling application's "App.Config". Hence I changed from Static to normal instantiated class . I followed the approach of configuring the path of my Logging config in the Application's config file. I got a feedback on how to use this from this thread (question-regarding-app-config-for-class-library-and-logging
I used this approach and everything worked perfectly fine when I use this Logger object in only one class
This is my approach (in nutshell):
- In my Main class (ex: Class A) I get the value from App.Config
I Initiate the Logger class with the constructor getting the path of the Configuration file
LogHandler = new LogHelper(logConfigFileLocation);
I use this
LogHandler
in my classclass A
I now stumble across this problem.
I have other classes Class B
and Class C
in which i want to use this LogHandler
. I use the Class B
and Class C
in Class A
If i do an instance of the LogHandler class, I would get a new log file.
How should i define my LogHandler Class? Should I go for a singleton a开发者_开发问答pproach?
Looking forward for some suggestions
Cheers,
Karthik
your loghandler-class should have a singleton factory method
public static LogHandler GetLogger()
that is called in every class.
Have whatever constructs Class A, Class B and Class C also create the instance of LogHandler. Then pass the reference to Class A, Class B and Class C.
Main
LogHandler logHandler = new LogHandler(params);
ClassA classA = new ClassA(params, ref logHandler);
ClassB classB = new ClassB(params, ref logHandler);
ClassA
LogHandler logHandler;
public ClassA(object[] params, ref LogHandler logHandlerRef)
{
logHandler = logHandlerRef;
}
Using this method the LogHandler is created only once and a reference is stored in each of the classes. Modification to any LogHandler in any class will modify them all. Only one log file will be created.
Depending on the structure of your program, you can make the LogHandler instance in Class A static and reference it from Class B and Class C (however, I do not recommend this approach).
Class A
public static LogHandler logHandler;
...
public ClassA()
{
logHandler = new LogHandler(params);
}
To use the loghandler in Class B or Class C
ClassA.logHandler.whateverMethod(params);
精彩评论