Siwar Siwar - 20 days ago 6
C# Question

more than one instance of singleton c#

Is there a realisation of a Singleton-like pattern which allows to create more than one instance?

My class definition is:

public class Logger
{
private Logger(string logPath)
{
this.logPath = logPath;
}


/// <summary>
/// Creates singleton
/// </summary>
/// <param name="logPath"></param>
/// <returns></returns>
public static Logger GetInstance(string logPath)
{
lock (instanceLock)
{
if (logger == null)
{
logger = new Logger(logPath);
}
}
return logger;
}

public static Logger Instance()
{
return logger;
}

/// <summary>
/// Destructor
/// </summary>
~Logger()
{
try
{
this.Close();
}
catch (Exception)
{
}
}
}

Answer

This is the pattern I use:

public class Logger
{
    private Logger(...) { ... }

    static Logger { /* initialize Errors, Warnings */ }

    public static Logger Errors { get; private set; }
    public static Logger Warnings { get; private set; }

    public void Write(string message) { ... }
}

If you want to have a static Logger Lookup(string name) method, you can do that too.

Now in other code you can write Logger.Errors.Write("Some error"); or Logger.Warnings.Write("Some warning");.

Bonus: you can use Environment.StackTrace inside of your Write method to additionally log what method you called Write from.