質問

I'm working with a class library where each class must share a single instance of a logger class. The logger is not mine, i.e. it is a dll I reference. Sharing is necessary because all messages have to be appended to the end of the single log message file that gets created when the logger is instantiated.

I thought about passing the logger class by reference after it is instantiated but this leads to some very ugly dependencies.

I'm under the gun and don't have a lot of time to experiment. Any suggestions on the best way to accomplish this? I'm thinking a static class might be the answer but any implementation I undertake will take some time and I don't want to head down a blind alley.

======================= UPDATE ===================

I decided this the quickest and cleanest way to handle this:

    public class Logger
{
    private static LoggerTool _loggerTool;

    public static void WriteLogMessage(string message)
    {

        if (_loggerTool == null)
        {
            // Create a new log file
            string logFileName = "LogFile-" + DateTime.Now.ToString("HHmmss");

            _loggerTool = new LoggerTool(logFileName);
        }

        _loggerTool.LogMessage(message);
    }
}

正しい解決策はありません

他のヒント

Creating a static class, and implementing singleton pattern would definitely work for you although it is not the cleanest way to approach it. Because of the coupling it makes it more difficult to unit test, etc.

Alternative approach would be to use Dependency Injection container such as autofac.

Here is a quick tutorial where they create use simple logger class with DI: http://stevescodingblog.co.uk/dependency-injection-beginners-guide/

Something like:

public static class LogManager
{
    private static Lazy<MyLog> logLazy = new Lazy<MyLog>(() => new MyLog());
    public static MyLog Log
    {
        get{
            return logLazy.Value;
        }
    }
}

then

LogManager.Log.Warning("blah") 

from anywhere in your code.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top